/* -----------------------------------------------------------------------------
 APPLICATION.JS
 Performs actions to improve visual presentation of the site.
 -----------------------------------------------------------------------------
 STARRING
 -------------------------------------------------------------------------- */

if (document.getElementById && document.getElementsByTagName && document.createTextNode) {
    create_mainNavCSSLink();
}

// Make sure that this page is displayed in the top frame and not in the Taleo IFrame (taleoIFrame)
if ((window.self != window.top) && (typeof(window.top.taleoIFrame) != undefined) && (window.self == window.top.taleoIFrame)) {
    window.top.location.href = window.location.href;
}

function init() {
    Element.addClassName(document.body, "jsEnabled");
}
/*String trim function*/
/*TODO: remove once prototype is updated to 1.5.0. The name of trim() is strip()*/
String.prototype.trim = function() {
    return this.replace(/^\s*|\s*$/g, "")
};

function addOnLoad(func) {
    Event.observe(window, "load", func);
}

function addOnUnload(func) {
    Event.observe(window, "unload", func);
}

addOnLoad(init);
addOnLoad(init_mainNav);
addOnLoad(init_faqs);
addOnLoad(init_foldunfolds);
addOnLoad(init_formSubmits);
addOnLoad(init_washCareSymbols);

var submenus = 0;

function ieHoverFix_on() {
    this.className = 'over';
}
;

function ieHoverFix_out() {
    this.className = '';
}
;

function create_mainNavCSSLink() {
    var link = document.createElement('LINK');
    link.rel = 'stylesheet';
    link.type = 'text/css';
    link.media = 'screen';
    link.href = '/static/css/common/js_specific.css';

    for (var i = 0; i < document.childNodes.length; i++) {
        if (document.childNodes[i].nodeName == 'HTML') {
            for (var k = 0; k < document.childNodes[i].childNodes.length; k++) {
                var curNode = document.childNodes[i].childNodes[k];
                if (curNode.nodeName == 'HEAD') {
                    curNode.appendChild(link);
                }
            }
        }
    }
}
;

/* MAIN NAVIGATION */

function init_mainNav() {
    if (nmObj = $('nav_main_object')) {
        for (var i = 0; i < nmObj.childNodes.length; i++) {
            var curObj = nmObj.childNodes[i];
            if ((curObj.nodeName == 'LI')) {
                for (var k = 0; k < curObj.childNodes.length; k++) {
                    var curObj2 = curObj.childNodes[k];
                    if (curObj2.nodeName == 'UL') {
                        for (var a = 0; a < curObj2.childNodes.length; a++) {
                            var curObj3 = curObj2.childNodes[a];
                            if ((curObj3.nodeName == 'LI') && !(curObj3.className.match(/current/))) {
                                for (var b = 0; b < curObj3.childNodes.length; b++) {
                                    var curObj4 = curObj3.childNodes[b];
                                    if (curObj4.nodeName == 'A') {
                                        if (curObj4.href == '#' || curObj4.href.indexOf('#') == curObj4.href.length - 1) {
                                            curObj4.onclick = show_subMenu;
                                        }
                                    }
                                    if (curObj4.nodeName == 'UL') {
                                        curObj4.id = 'submenu_' + submenus;
                                        submenus++;
                                    }
                                }
                            }
                        }
                    } else if ((curObj2.nodeName == 'A') && !(curObj.className.match(/current/))) {
                        curObj2.firstlevel = true;
                        if (curObj2.href == '#' || curObj2.href.indexOf('#') == curObj2.href.length - 1) {
                            curObj2.onclick = show_subMenu;
                        }
                    }
                }
            }
        }
    }
}
;

function show_subMenu() {
    for (var i = 0; i < this.parentNode.childNodes.length; i++) {
        var curObj = this.parentNode.childNodes[i];
        if (curObj.nodeName == 'UL') {
            if (!curObj.className) {
                for (var k = 0; k < submenus; k++) {
                    document.getElementById('submenu_' + k).className = '';
                }
                curObj.className = 'show';
                if (this.firstlevel) {
                    var nmObj = $('nav_main_object');
                    for (var k = 0; k < nmObj.childNodes.length; k++) {
                        var curObj2 = nmObj.childNodes[k];
                        if ((curObj2.nodeName == 'LI') && (curObj2.className == 'current expanded')) {
                            curObj2.className = '';
                            for (var a = 0; a < curObj2.childNodes.length; a++) {
                                var curObj3 = curObj2.childNodes[a];
                                if (curObj3.nodeName == 'UL') {
                                    curObj3.className = '';
                                }
                            }
                        }
                    }
                    this.parentNode.className = 'current expanded';
                }
            } else {
                if (this.firstlevel) {
                    this.parentNode.className = '';
                }
                curObj.className = '';
            }
        }
    }
}
;

/* FAQs */

//TODO This should be removed and we should use the generic named function "foldunfold" instead /m
function init_faqs() {
    var DLs;
    if (DLs = document.getElementsByTagName('DL')) {
        for (var i = 0; i < DLs.length; i++) {
            if (DLs[i].className.match(/faq/)) {
                DLs[i].id = 'faq_' + i;
                var DTs = DLs[i].getElementsByTagName('DT');
                var DDs = DLs[i].getElementsByTagName('DD');
                for (var k = 0; k < DTs.length; k++) {
                    var DTtext = DTs[k].firstChild.data;
                    var DTlink = document.createElement('A');
                    DTlink.onclick = showhide_dd;
                    DTlink.appendChild(document.createTextNode(DTtext));
                    DTlink.faqid = DLs[i].id;
                    DTlink.thisnum = k;
                    DTs[k].replaceChild(DTlink, DTs[k].firstChild);
                }
            }
        }
    }
}
;

function init_foldunfolds() {
    var DLs;
    if (DLs = document.getElementsByTagName('DL')) {
        for (var i = 0; i < DLs.length; i++) {
            if (DLs[i].className.match(/foldunfold/)) {
                DLs[i].id = 'foldunfold' + i;
                var DTs = DLs[i].getElementsByTagName('DT');
                var DDs = DLs[i].getElementsByTagName('DD');
                for (var k = 0; k < DTs.length; k++) {
                    var DTtext = DTs[k].firstChild.data;
                    var DTlink = document.createElement('A');
                    DTlink.onclick = showhide_dd;
                    DTlink.appendChild(document.createTextNode(DTtext));
                    DTlink.faqid = DLs[i].id;
                    DTlink.thisnum = k;
                    DTs[k].replaceChild(DTlink, DTs[k].firstChild);
                }
            }
        }
    }
}
;

function showhide_dd() {
    if (DL = $(this.faqid)) {
        var thisnum = this.thisnum;
        var DTs = DL.getElementsByTagName('DT');
        var DDs = DL.getElementsByTagName('DD');
        DDs[thisnum].className = (DDs[thisnum].className == '') ? 'show' : '';
        this.className = (this.className == '') ? 'current' : '';
    }
}
;

/* FORM SUBMITS */

function init_formSubmits() {

    var allInputs = document.getElementsByTagName('INPUT');
    var allSubmits = new Array();
    for (var i = 0; i < allInputs.length; i++) {
        if (allInputs[i].type == 'submit') {
            allSubmits[allSubmits.length] = allInputs[i];
        }
    }

    for (var i = 0; i < allSubmits.length; i++) {
        var submit = allSubmits[i];
        initSubmit(submit);
    }
}
;

function initSubmit(submit) {
    var form = submit.form;

    var theLink = document.createElement('A');
    if (submit.disabled) {
        theLink.className = "buttondisabled " + submit.className;
    } else {
        theLink.className = "button " + submit.className;
        if (form.id.lastIndexOf('download_pdf') != -1) {
            theLink.onclick = submitToNewWin;
        } else {
            theLink.onclick = submitForm;
        }
    }

    theLink.formId = form.id;
    theLink.id = "ahrefsubmit_" + i + "_" + submit.id;

    theLink.oldonclick = null;
    if (submit.onclick != null) {
        theLink.oldonclick = submit.onclick;
    }

    if (form.id.lastIndexOf('download_pdf') != -1) {
        theLink.onclick = submitToNewWin;
    } else {
        theLink.onclick = submitForm;
    }


    if (submit.onmouseover != null)
        theLink.onmouseover = submit.onmouseover;
    if (submit.onmouseout != null)
        theLink.onmouseout = submit.onmouseout;

    var theSpan = document.createElement('SPAN');
    var dummyElement = document.createElement('TEST');
    dummyElement.appendChild(document.createTextNode(submit.value));
    theSpan.appendChild(dummyElement);
    theLink.appendChild(theSpan);

    submit.className += " hidden";
    submit.parentNode.appendChild(theLink);
}

function submitForm() {
    if (this.oldonclick != null) {
        this.oldonclick();
    }
    if ($(this.formId).onsubmit != null) {
        $(this.formId).onsubmit();
    }

    $(this.formId).submit();
}
;

function submitToNewWin() {
    if (this.oldonclick != null)
        this.oldonclick();
    var allForms = document.getElementsByTagName('FORM');
    var form;
    for (var i = 0; i < allForms.length; i++) {
        if (allForms[i].id == this.formId) {
            form = allForms[i];
            break;
        }
    }
    var accessName = form.accessname.value;
    var url = form.action + '?accessname=' + accessName;
    window.open(url);
    return false;
}
;

/* WASH CARE SYMBOLS */

function init_washCareSymbols() {
    if (wcList = $('wash_care_symbols_list')) {
        var IMGs = wcList.getElementsByTagName('IMG');
        for (var i = 0; i < IMGs.length; i++) {
            IMGs[i].onclick = show_wcPopup;
            IMGs[i].onmouseover = ieHoverFix_on;
            IMGs[i].onmouseout = ieHoverFix_out;
        }
    }

    if (wcDiv = $('wash_care_symbol_descriptions')) {
        var wcDivs = wcDiv.getElementsByTagName('DIV');

        for (var i = 0; i < wcDivs.length; i++) {
            if (wcDivs[i].className.match(/wash_care_symbol_description/)) {
                var link = document.createElement('A');
                link.appendChild(document.createTextNode('Close'));
                link.onclick = hide_wcPopup;
                link.className = 'close_popup';

                var twoCols = wcDivs[i].getElementsByTagName('DIV')[0];
                var header = twoCols.getElementsByTagName('H4')[0];
                twoCols.insertBefore(link, header);
            }
        }
    }
}
;

function show_wcPopup() {
    var popupId = this.id.replace('_trigger', '');
    if (popup = $(popupId)) {
        if (!(popup.className.match(/ show/))) {
            if (wcDiv = $('wash_care_symbol_descriptions')) {
                wcDivs = wcDiv.getElementsByTagName('DIV');
                for (var i = 0; i < wcDivs.length; i++) {
                    if (wcDivs[i].className.match(/ show/)) {
                        wcDivs[i].className = wcDivs[i].className.replace(' show', '');
                    }
                }
            }
            popup.className += ' show';
        }
    }
}
;

function hide_wcPopup() {
    popup = this.parentNode.parentNode;
    if (popup.className.match(/ show/)) {
        popup.className = popup.className.replace(' show', '');
    }
}
;

/* IMAGE GALLERIES */

addOnLoad(init_imageGalleries);

function init_imageGalleries() {

    if (Prototype && (ajaxObj = new Ajax.Request)) {
        // Check to see which DIVs are image galleries (if any)
        var DIVs = document.getElementsByTagName('DIV');
        var galleries = 0;
        var galleryType;
        for (var i = 0; i < DIVs.length; i++) {
            if (DIVs[i].className.match(/image_gallery/) || DIVs[i].className.match(/mini_image_gallery/) || DIVs[i].className.match(/image_gallery2/)) {
                galleries++;
                DIVs[i].id = 'gallery_' + galleries;
            }
        }

        // Loop through the links in each gallery and prepare them for AJAX integration
        for (var i = 0; i < galleries; i++) {

            regexp = /image=([0-9]*)$/;
            gallery = $('gallery_' + (i + 1));
            links = gallery.getElementsByTagName('A');
            for (var k = 0; k < links.length; k++) {
                if (links[k].image_id = regexp.exec(links[k].href)[1]) {
                    //alert("image_id=" + links[k].image_id);
                    links[k].removeAttribute('href');
                    links[k].onclick = show_imageDownload2;
                    links[k].onmouseout = ieHoverFix_out;
                    links[k].onmouseover = ieHoverFix_on;
                    links[k].picturepath = links[k].getElementsByTagName("img")[0].src;
                }
            }
        }

        // Create a DIV to be the Download Dialog
        if ($('gallery_1')) {
            var fakewin = document.createElement('DIV');
            var win = document.createElement('DIV');
            fakewin.id = 'gallery_fake_dl_window';
            win.id = 'gallery_dl_window';
            $('gallery_1').parentNode.insertBefore(fakewin, $('gallery_1'));
            $('gallery_1').parentNode.insertBefore(win, $('gallery_1'));
            reset_galleryDlWindow();
        }
    }
}
;

function reset_galleryDlWindow2(ajaxResponse) {
    if (win = $('gallery_dl_window')) {
        while (win.hasChildNodes()) {
            win.removeChild(win.firstChild);
        }

        var link = document.createElement('A');
        var header = document.createElement('H4');
        var pic_p = document.createElement('P');
        var pic = document.createElement('IMG');
        var description = document.createElement('P');
        var photographer_label = document.createElement('SPAN');
        var photographer = document.createElement('SPAN');
        var price_label = document.createElement('SPAN');
        var price = document.createElement('SPAN');
        var terms_p = document.createElement('P');
        var terms_label = document.createElement('LABEL');
        var terms_checkbox = document.createElement('INPUT');
        var terms_part1 = document.createElement('SPAN');
        var terms_link = document.createElement('A');
        var highres_p = document.createElement('P');
        var lowres_p = document.createElement('P');
        var highres_link = document.createElement('A');
        var lowres_link = document.createElement('A');
        var highres_span = document.createElement('SPAN');
        var lowres_span = document.createElement('SPAN');
        var instructions = document.createElement('P');
        var right_div = document.createElement('DIV');

        header.id = 'gallery_dl_header';
        pic.id = 'gallery_dl_pic';
        description.id = 'gallery_dl_description';
        photographer_label.id = 'gallery_dl_photographer_label';
        photographer.id = 'gallery_dl_photographer';
        price_label.id = 'gallery_dl_price_label';
        price.id = 'gallery_dl_price';
        terms_p.id = 'gallery_dl_terms';
        terms_part1.id = 'gallery_dl_terms_part1';
        terms_link.id = 'privacy_policy_link';
        highres_p.id = 'gallery_dl_highres';
        lowres_p.id = 'gallery_dl_lowres';
        highres_link.id = 'gallery_dl_highres_link';
        lowres_link.id = 'gallery_dl_lowres_link';
        highres_span.id = 'gallery_dl_highres_span';
        lowres_span.id = 'gallery_dl_lowres_span';
        instructions.id = 'gallery_dl_instructions';
        right_div.id = 'gallery_dl_rightdiv';
        pic_p.className = 'gallery_dl_picture';
        pic.alt = '';

        link.appendChild(document.createTextNode('Close'));
        link.onclick = hide_imageDownload;
        link.className = 'close_popup';

        header.appendChild(document.createTextNode(' '));

        pic_p.appendChild(pic);
        description.appendChild(document.createTextNode(' '));
        //photographer.appendChild(document.createTextNode(' '));
        //price.appendChild(document.createTextNode(' '));
        instructions.appendChild(document.createTextNode(' '));
        terms_checkbox.onclick = allow_imageDownload;

        terms_checkbox.id = 'gallery_dl_terms_checkbox';
        terms_checkbox.type = 'checkbox';
        terms_link.href = 'javascript:showPressImagePolicyPopup();';
        terms_label.appendChild(document.createTextNode(' '));
        terms_label.appendChild(terms_part1);
        terms_label.appendChild(document.createTextNode(' '));
        terms_label.appendChild(terms_link);
        terms_p.appendChild(terms_checkbox);
        terms_p.appendChild(terms_label);

        highres_link.appendChild(document.createTextNode(' '));
        highres_span.appendChild(document.createTextNode(' '));
        highres_link.appendChild(document.createTextNode(' '));
        highres_link.appendChild(highres_span);
        highres_p.appendChild(highres_link);
        lowres_link.appendChild(document.createTextNode(' '));
        lowres_span.appendChild(document.createTextNode(' '));
        lowres_link.appendChild(document.createTextNode(' '));
        lowres_link.appendChild(lowres_span);
        lowres_p.appendChild(lowres_link);

        win.appendChild(link);
        win.appendChild(header);
        win.appendChild(pic_p);

        right_div.appendChild(description);
        right_div.appendChild(photographer_label);
        right_div.appendChild(photographer);
        right_div.appendChild(price_label);
        right_div.appendChild(price);
        win.appendChild(right_div);

        var lowresElement = ajaxResponse.getElementsByTagName('picture')[0].getElementsByTagName('lowres')[0].firstChild;
        var highresElement = ajaxResponse.getElementsByTagName('picture')[0].getElementsByTagName('highres')[0].firstChild;

        if ((lowresElement != null && lowresElement.nodeValue.trim() != "") ||
                (highresElement != null && highresElement.nodeValue.trim() != "")) {

            right_div.appendChild(instructions);
            right_div.appendChild(terms_p);
        }

        if (highresElement != null && highresElement.nodeValue.trim() != "") {
            right_div.appendChild(highres_p);
        }
        if (lowresElement != null && lowresElement.nodeValue.trim() != "") {
            right_div.appendChild(lowres_p);
        }

    }
}
;

function show_imageDownload2(e) {
    if (win = $('gallery_dl_window')) {
        var ajax = new Ajax.Request(
                'viewarchivepic2.ahtml',
        {
            method: 'post',
            parameters: 'image=' + this.image_id,
            onSuccess: show_imageDownload_done2,
            onFailure: show_imageDownload_error
        });


        fakewin = $('gallery_fake_dl_window');

        while (win.hasChildNodes()) {
            win.removeChild(win.firstChild);
        }

        var loader_p = document.createElement('P');
        var loader_img = document.createElement('IMG');

        loader_p.id = 'gallery_dl_loader';

        loader_img.src = '/static/images/common/ajax_loader.gif';
        loader_p.appendChild(loader_img);
        win.appendChild(loader_p);

        var evt = e ? e : window.event;
        var posx = Event.pointerX(evt);
        var posy = Event.pointerY(evt);

        if (posx > 725) posx = 725;
        if (posx < 460) posx = 460;

        galleryWinPosX = posx - 239;
        galleryWinPosY = posy - 167;

        win.style.left = galleryWinPosX + 'px';
        fakewin.style.left = galleryWinPosX + 'px';
        win.style.top = galleryWinPosY + 'px';
        fakewin.style.top = galleryWinPosY + 'px';

        if (!win.className.match(/ show/)) {
            win.className += ' show';
            fakewin.className += ' show';
        }

        if (this.picturepath.indexOf("copyrightcampaign") != -1) {
            showDynamicPolicyPopup(e, '/static/temp/copyrightcampaign.html');
        }
        if (this.picturepath.indexOf("copyrightevent") != -1) {
            showDynamicPolicyPopup(e, '/static/temp/copyrightevent.html');
        }

        if (this.image_id.indexOf("501_1") != -1) {
            showDynamicPolicyPopup(e, '/static/temp/kmtext.html');
        }
        if (this.image_id.indexOf("501_2") != -1) {
            showDynamicPolicyPopup(e, '/static/temp/kmtext2.html');
        }

    }
}
;

function show_imageDownload_done2(response) {
    //TODO: Move this to CSS once old popup is gone.
    var win = $('gallery_dl_window');
    var fakewin = $('gallery_fake_dl_window');
    win.style.height = '415px';
    fakewin.style.height = '415px';

    var ajaxResponse = Try.these(
            function() {
                return new DOMParser().parseFromString(response.responseText, 'text/xml');
            },
            function() {
                var xmldom = new ActiveXObject('Microsoft.XMLDOM');
                xmldom.loadXML(response.responseText);
                return xmldom;
            }
            );
    reset_galleryDlWindow2(ajaxResponse);
    var header = $('gallery_dl_header');
    pic = $('gallery_dl_pic');
    var description = $('gallery_dl_description');
    photographer_label = $('gallery_dl_photographer_label');
    photographer = $('gallery_dl_photographer');
    price_label = $('gallery_dl_price_label');
    price = $('gallery_dl_price');
    terms = $('gallery_dl_terms');
    terms_part1 = $('gallery_dl_terms_part1');
    terms_link = $('privacy_policy_link');
    highres_link = $('gallery_dl_highres_link');
    highres_span = $('gallery_dl_highres_span');
    lowres_link = $('gallery_dl_lowres_link');
    lowres_span = $('gallery_dl_lowres_span');
    instructions = $('gallery_dl_instructions');

    pic.width = 167;
    pic.heigth = 216;

    header.replaceChild(document.createTextNode(ajaxResponse.getElementsByTagName('header')[0].firstChild.nodeValue), header.firstChild);
    pic.src = ajaxResponse.getElementsByTagName('picture')[0].getElementsByTagName('bigger_picture')[0].firstChild.nodeValue;

    var descriptionElement = ajaxResponse.getElementsByTagName('picture')[0].getElementsByTagName('description')[0].firstChild.nodeValue;
    if (descriptionElement != null && descriptionElement.trim() != '') {
        description.appendChild(document.createTextNode(ajaxResponse.getElementsByTagName('picture')[0].getElementsByTagName('description')[0].firstChild.nodeValue));
        description.appendChild(document.createElement('BR'));
        description.style.display = 'block';
    }
    else if (descriptionElement != null) {
        description.style.display = 'none';
    }

    var photographerElement = ajaxResponse.getElementsByTagName('photographer')[0].firstChild.nodeValue;
    if (photographerElement != null && photographerElement.trim() != '') {
        photographer_label.appendChild(document.createTextNode(ajaxResponse.getElementsByTagName('photographer_label')[0].firstChild.nodeValue));
        photographer.appendChild(document.createTextNode(ajaxResponse.getElementsByTagName('picture')[0].getElementsByTagName('photographer')[0].firstChild.nodeValue));
        photographer.appendChild(document.createElement('BR'));
    }

    var priceElement = ajaxResponse.getElementsByTagName('price')[0].firstChild.nodeValue;
    if (priceElement != null && priceElement.trim() != '') {
        price_label.appendChild(document.createTextNode(ajaxResponse.getElementsByTagName('price_label')[0].firstChild.nodeValue));
        price.appendChild(document.createTextNode(ajaxResponse.getElementsByTagName('picture')[0].getElementsByTagName('price')[0].firstChild.nodeValue));
        price.appendChild(document.createElement('BR'));
    }

    terms_part1.appendChild(document.createTextNode(ajaxResponse.getElementsByTagName('terms_part1')[0].firstChild.nodeValue.trim()));
    terms_link.appendChild(document.createTextNode(ajaxResponse.getElementsByTagName('terms_part2')[0].firstChild.nodeValue.trim()));


    var highresElement = ajaxResponse.getElementsByTagName('picture')[0].getElementsByTagName('highres')[0].firstChild;
    if (highresElement != null && highresElement.nodeValue.trim() != "") {
        highres_link.replaceChild(document.createTextNode(ajaxResponse.getElementsByTagName('highres_text')[0].firstChild.nodeValue), highres_link.firstChild)
        highres_link.linkto = ajaxResponse.getElementsByTagName('picture')[0].getElementsByTagName('highres')[0].firstChild.nodeValue;
        highres_span.replaceChild(document.createTextNode('(' + ajaxResponse.getElementsByTagName('picture')[0].getElementsByTagName('highres_size')[0].firstChild.nodeValue + ')'), highres_span.firstChild)
    }

    var lowresElement = ajaxResponse.getElementsByTagName('picture')[0].getElementsByTagName('lowres')[0].firstChild;
    if (lowresElement != null && lowresElement.nodeValue.trim() != "") {
        lowres_link.replaceChild(document.createTextNode(ajaxResponse.getElementsByTagName('lowres_text')[0].firstChild.nodeValue), lowres_link.firstChild)
        lowres_link.linkto = ajaxResponse.getElementsByTagName('picture')[0].getElementsByTagName('lowres')[0].firstChild.nodeValue;
        lowres_span.replaceChild(document.createTextNode('(' + ajaxResponse.getElementsByTagName('picture')[0].getElementsByTagName('lowres_size')[0].firstChild.nodeValue + ')'), lowres_span.firstChild)
    }

    instructions.replaceChild(document.createTextNode(ajaxResponse.getElementsByTagName('instructions')[0].firstChild.nodeValue), instructions.firstChild)

}
;

function allow_imageDownload() {
    var highres_link = $('gallery_dl_highres_link');
    var lowres_link = $('gallery_dl_lowres_link');
    var terms_checkbox = $('gallery_dl_terms_checkbox');
    if (terms_checkbox.checked) {
        if (highres_link != null) {
            highres_link.href = highres_link.linkto;
            highres_link.className = 'active';
            highres_link.setAttribute('onmousedown', 'trackElementEvent("Highres_Allow_Image_download", "Gallery")');
        }
        if (lowres_link != null) {
            lowres_link.href = lowres_link.linkto;
            lowres_link.className = 'active';
            lowres_link.setAttribute('onmousedown', 'trackElementEvent("Lowres_Allow_Image_download", "Gallery")');
        }
    } else {
        if (highres_link != null) {
            highres_link.removeAttribute('href');
            highres_link.className = '';
            highres_link.removeAttribute('onmousedown');
        }
        if (lowres_link != null) {
            lowres_link.removeAttribute('href');
            lowres_link.className = '';
            lowres_link.removeAttribute('onmousedown');
        }
    }
}

function show_imageDownload_error() {
    hide_imageDownload();
    alert('There was an error while loading the details for this picture. Please try again later.');
}
;

function hide_imageDownload() {
    if (win = $('gallery_dl_window')) {
        fakewin = $('gallery_fake_dl_window');
        if (win.className.match(/ show/)) {
            hidePolicyPopup();
            win.className = win.className.replace(' show', '');
            fakewin.className = fakewin.className.replace(' show', '');
        }
        if (win.className.match(/show/)) {
            hidePolicyPopup();
            win.className = win.className.replace('show', '');
            fakewin.className = fakewin.className.replace('show', '');
        }
    }
}
;


/* EXTERNAL LINKS */

addOnLoad(init_extLinks);

function init_extLinks() {
    if (links = document.getElementsByTagName('A')) {
        for (var i = 0; i < links.length; i++) {
            var link = links[i];
            if (link.rel == 'external') {
                link.onclick = extLink;
            }
        }
    }
}
;

function extLink() {
    window.open(this.href);
    return false;
}
;

/*PRIVACY POLICY*/
addOnLoad(init_PrivacyPolicy);
addOnLoad(init_ImagePrivacyPolicy);
addOnLoad(init_ContactConditionsPolicy);

var ppPosX = 0;
var ppPosY = 0;
var galleryWinPosX = null;
var galleryWinPosY = null;

function init_PrivacyPolicy() {
    if (document.getElementsByClassName('privacy_policy_link') != null && typeof(document.getElementsByClassName('privacy_policy_link')) != undefined) {
        //Find all privacy policy and add an onclick event
        var ppLinks = document.getElementsByClassName('privacy_policy_link')
        for (var k = 0; k < ppLinks.length; k++) {
            ppLinks[k].onclick = showPrivacyPolicyPopup;
        }
    }
}
;

function init_ContactConditionsPolicy() {
    if (document.getElementsByClassName('contact_conditions_policy_link') != null && typeof(document.getElementsByClassName('contact_conditions_policy_link')) != undefined) {
        //Find all privacy policy and add an onclick event
        var ppLinks = document.getElementsByClassName('contact_conditions_policy_link')
        for (var k = 0; k < ppLinks.length; k++) {
            ppLinks[k].onclick = showContactConditionsPolicyPopup;
        }
    }
}
;


function init_ImagePrivacyPolicy() {
    if (document.getElementsByClassName('image_policy_link') != null && typeof(document.getElementsByClassName('image_policy_link')) != undefined) {
        //Find all privacy policy and add an onclick event
        var ppLinks = document.getElementsByClassName('image_policy_link')
        for (var k = 0; k < ppLinks.length; k++) {
            ppLinks[k].onclick = showPressImagePolicyPopup;
        }
    }
}
;


function showDynamicPolicyPopup(e, source) {
    if (Prototype && (ajaxObj = new Ajax.Request)) {
        //Dynamic positioning
        var evt = e ? e : window.event;
        ppPosX = Event.pointerX(evt);
        ppPosY = Event.pointerY(evt);

        if (ppPosX > 725) ppPosx = 725;
        if (ppPosX < 460) ppPosx = 460;

        var ajax = new Ajax.Request(
                source,
        {

            method: 'post',
            onSuccess: showPolicyPopupDone,
            onFailure: showPrivacyPolicyPopupError
        });
    }
}
;

function showPressImagePolicyPopup(e) {
    if (Prototype && (ajaxObj = new Ajax.Request)) {
        /*If policy popup is not opened from a gallery popup, position it based on mouse pointer*/
        if ($('gallery_dl_window') == null && $('video_gallery_dl_window') == null) {
            //Dynamic positioning
            var evt = e ? e : window.event;
            ppPosX = Event.pointerX(evt);
            ppPosY = Event.pointerY(evt);

            if (ppPosX > 725) ppPosx = 725;
            if (ppPosX < 460) ppPosx = 460;
        }

        var resource;
        resource = 'pressimagepolicypopup.ahtml';
        if ($("archiveType")) {
            var archiveType = $("archiveType").innerHTML;
            if (archiveType && archiveType == "video") {
                resource = 'pressvideopolicypopup.ahtml';
            }
        }

        /*
         if (win = $('video_gallery_dl_window')) {
         if(win.className.match(/show/)){
         resource = 'pressvideopolicypopup.ahtml';
         }
         }
         if (win = $('gallery_dl_window')) {
         if(win.className.match(/show/)){
         resource = 'pressimagepolicypopup.ahtml';
         }
         }*/


        var ajax = new Ajax.Request(
                resource,
        {

            method: 'post',
            onSuccess: showPolicyPopupDone,
            onFailure: showPressImagePolicyPopupError
        });

    }
}

function showPressVideoPolicyPopupFromPage(event) {
    if (Prototype && (ajaxObj = new Ajax.Request)) {

        var resource = 'pressvideopolicypopup.ahtml';

        var ajax = new Ajax.Request(
                resource,
        {

            method: 'post',
            onSuccess: showPolicyPopupDone,
            onFailure: showPressImagePolicyPopupError
        });

    }
}

function showPrivacyPolicyPopup(e) {
    if (Prototype && (ajaxObj = new Ajax.Request)) {
        //Dynamic positioning
        var evt = e ? e : window.event;
        ppPosX = Event.pointerX(evt);
        ppPosY = Event.pointerY(evt);

        if (ppPosX > 725) ppPosx = 725;
        if (ppPosX < 460) ppPosx = 460;

        var ajax = new Ajax.Request(
                'privacypolicypopup.ahtml',
        {

            method: 'post',
            onSuccess: showPolicyPopupDone,
            onFailure: showPrivacyPolicyPopupError
        });
    }
}
;

function showContactConditionsPolicyPopup(e) {
    if (Prototype && (ajaxObj = new Ajax.Request)) {
        //Dynamic positioning
        var evt = e ? e : window.event;
        ppPosX = Event.pointerX(evt);
        ppPosY = Event.pointerY(evt);

        if (ppPosX > 725) ppPosx = 725;
        if (ppPosX < 460) ppPosx = 460;

        var ajax = new Ajax.Request(
                'contactconditionspolicypopup.ahtml',
        {

            method: 'post',
            onSuccess: showPolicyPopupDone,
            onFailure: showContactConditionsPolicyPopupError
        });
    }
}
;


function showPolicyPopupDone(response) {
    fakePPwin = createPolicyPopup();
    fakePPwin.innerHTML = response.responseText;
    fakePPwin.style.visibility = 'visible';
    $('policy_fakewin_back').style.visibility = 'visible';
}
;
function hidePolicyPopup() {
    if (fakePPwin = $('policy_fakewin')) {
        var fakePPwin = $('policy_fakewin');
        fakePPwin.parentNode.removeChild(fakePPwin);
    }
    if (fakePPwinBack = $('policy_fakewin_back')) {
        var fakePPwinBack = $('policy_fakewin_back');
        fakePPwinBack.parentNode.removeChild(fakePPwinBack)
    }
    showSelectBoxes();
}
;
//Create a DIV to be the Privacy Policy Popup
function createPolicyPopup() {
    var ppWinBack;
    var ppWin;

    //Window does not exist - create one.
    if ($('policy_fakewin') == null || $('policy_fakewin_back') == null) {
        ppWinBack = document.createElement('DIV');
        ppWinBack.id = 'policy_fakewin_back'
        ppWin = document.createElement('DIV');
        ppWin.id = 'policy_fakewin';

        //Window does already exist - get the old one.
    } else {
        ppWinBack = $('policy_fakewin_back');
        ppWin = $('policy_fakewin');
    }

    //Window is on top of the gallery_dl_window, set window position relative to the parent
    if (($('gallery_dl_window') != null || $('video_gallery_dl_window') != null) && galleryWinPosX && galleryWinPosY) {
        ppWinBack.style.left = galleryWinPosX - 75 + 'px';
        ppWin.style.left = galleryWinPosX - 75 + 'px';
        ppWinBack.style.top = Math.max(galleryWinPosY + 75, 0) + 'px';
        ppWin.style.top = Math.max(galleryWinPosY + 75, 0) + 'px';

    } else if ($('policy_fakewin') != null || ppWin.id == 'policy_fakewin') {

        ppWinBack.style.left = ppPosX - 80 + 'px';
        ppWin.style.left = ppPosX - 80 + 'px';
        ppWinBack.style.top = Math.max(ppPosY - 380, 0) + 'px';
        ppWin.style.top = Math.max(ppPosY - 380, 0) + 'px';

        //Set window position based on mouse coordinates
    } else {
        ppWinBack.style.left = ppPosX + 'px';
        ppWin.style.left = ppPosX + 'px';
        ppWinBack.style.top = Math.max(ppPosY + 'px', 0);
        ppWin.style.top = Math.max(ppPosY + 'px', 0);
    }

    //
    hideSelectBoxes();
    //It is not possible to insert this new element under its parent bacause that
    //might be a <label> which causes problems with IE 6.0. Instead we append it to content.
    $('content').appendChild(ppWinBack);
    $('content').appendChild(ppWin);

    return ppWin;
}
;
function showPrivacyPolicyPopupError() {
    hidePolicyPopup();
    alert('There was an error while loading the privacy policy. Please try again later.');
}
;

function showContactConditionsPolicyPopupError() {
    hidePolicyPopup();
    alert('There was an error while loading the contact condition policy. Please try again later.');
}
;


function showPressImagePolicyPopupError() {
    hidePolicyPopup();
    alert('There was an error while loading the terms for using images. Please try again later.');
}
;

function showSelectBoxes() {
    elmtSelect = document.getElementsByTagName('SELECT');
    for (var i = 0; i < elmtSelect.length; i++) {
        elmtSelect[i].style.visibility = 'visible';
    }
}
function hideSelectBoxes() {
    elmtSelect = document.getElementsByTagName('SELECT');
    for (var i = 0; i < elmtSelect.length; i++) {
        elmtSelect[i].style.visibility = 'hidden';
    }
}


/* POPUP OPENER */
function openFullScreenPopup(url, windowName) {

    var faqWindowName = 'faqworkathm';
    var careerNavigationNodePrefix = 'career';
    var left = 0;
    var top = 0;
    var width, height;
    var isMac = (navigator.appVersion.indexOf("Mac") != -1);

    width = (screen.availWidth ? screen.availWidth : 800);
    height = (screen.availHeight ? screen.availHeight : 600);

    height -= 10;
    width -= 10;
    if (isMac) {
        height -= 20;
    }

    if (windowName != null && windowName.indexOf(faqWindowName) != -1) {
        width = 480;
        height = 600;
        left = 500;
        top = 112;
    }
    if (windowName != null && windowName.startsWith(careerNavigationNodePrefix)) {
        width = 600;
        height = 550;
        left = 230;
        top = 50;
    }

    if (windowName == null || windowName == "") {
        windowName = "popupFullscreen";
    }

    var windowAttributes = "left=" + left
            + ",top=" + top
            + ", width=" + width
            + ", height=" + height
            + ", fullscreen=" + 'no'
            + ", toolbar=" + 'no'
            + ", location=" + 'no'
            + ", status=" + 'no'
            + ", menubar=" + 'no'

    if (windowName != null && (windowName.indexOf(faqWindowName) != -1 || windowName.startsWith(careerNavigationNodePrefix))) {
        windowAttributes += ", scrollbars=" + 'yes'
    } else {
        windowAttributes += ", scrollbars=" + 'no'
    }

    windowAttributes += ", resizable=" + 'no'
            + ", copyhistory=" + 'no'

    //Track this pageview
    trackFlashPageView("POPUP : " + windowName, "corp:lightbox", null, null, url);
    if ((windowName != null) && windowName.startsWith(careerNavigationNodePrefix) && (typeof showLightbox == 'function')) {
        showLightbox({lightBoxClass: 'lightboxCAREER',url:url + '?popup=true', 'width': width, 'height': height, 'left':left, 'top':top,
            loadingErrorMessage: lightboxLoadingErrorMessage});
    } else {
        var theWindow = window.open(url, windowName, windowAttributes);
        if (theWindow != null) {
            theWindow.focus();
        }
    }

}
;

function openPopup(ppage, pname, pwidth, pheight, pt, pl, ptol, pr, ps, ploc) {
    newwin = window.open(ppage, pname, "toolbar=" + ptol + ",location=" + ploc + ", resizable=" + pr + ",scrollbars=" + ps + ",width=" + pwidth + ",height=" + pheight + ",top=" + pt + ",left=" + pl)
    if (newwin.opener == null) {
        newwin.opener = self;
    }
    newwin.focus();
}
;

function openPDF() {
    return false;
}
;

function toggleExpansion(e) {
    var evt = e ? e : window.event;

    var prototypedElement = $(Event.element(evt));

    //propagate upwards in the dom tree if the event originated at a child
    while (!Element.hasClassName(prototypedElement, "collapsed") && !Element.hasClassName(prototypedElement, "expanded")) {
        prototypedElement = $(prototypedElement.parentNode);
    }
    if (Element.hasClassName(prototypedElement, "collapsed")) {
        Element.removeClassName(prototypedElement, "collapsed");
        Element.addClassName(prototypedElement, "expanded");
    } else {
        Element.removeClassName(prototypedElement, "expanded");
        Element.addClassName(prototypedElement, "collapsed");
    }
}
;


function reset_galleryDlWindow() {
    if (win = $('gallery_dl_window')) {
        while (win.hasChildNodes()) {
            win.removeChild(win.firstChild);
        }

        var link = document.createElement('A');
        var header = document.createElement('H4');
        var pic_p = document.createElement('P');
        var pic = document.createElement('IMG');
        var photographer = document.createElement('P');
        var terms_p = document.createElement('P');
        var terms_label = document.createElement('LABEL');
        var terms_checkbox = document.createElement('INPUT');
        var terms_part1 = document.createElement('SPAN');
        var terms_link = document.createElement('A');
        var highres_p = document.createElement('P');
        var lowres_p = document.createElement('P');
        var highres_link = document.createElement('A');
        var lowres_link = document.createElement('A');
        var highres_span = document.createElement('SPAN');
        var lowres_span = document.createElement('SPAN');
        var instructions = document.createElement('P');

        header.id = 'gallery_dl_header';
        pic.id = 'gallery_dl_pic';
        photographer.id = 'gallery_dl_photographer';
        terms_p.id = 'gallery_dl_terms';
        terms_part1.id = 'gallery_dl_terms_part1';
        terms_link.id = 'privacy_policy_link';
        highres_p.id = 'gallery_dl_highres';
        lowres_p.id = 'gallery_dl_lowres';
        highres_link.id = 'gallery_dl_highres_link';
        lowres_link.id = 'gallery_dl_lowres_link';
        highres_span.id = 'gallery_dl_highres_span';
        lowres_span.id = 'gallery_dl_lowres_span';
        instructions.id = 'gallery_dl_instructions';

        pic_p.className = 'gallery_dl_picture';
        pic.alt = '';

        link.appendChild(document.createTextNode('Close'));
        link.onclick = hide_imageDownload;
        link.className = 'close_popup';

        header.appendChild(document.createTextNode(' '));

        pic_p.appendChild(pic);

        photographer.appendChild(document.createTextNode(' '));
        instructions.appendChild(document.createTextNode(' '));
        terms_checkbox.onclick = allow_imageDownload;

        terms_checkbox.id = 'gallery_dl_terms_checkbox';
        terms_checkbox.type = 'checkbox';
        terms_link.href = 'javascript:showPressImagePolicyPopup();';
        terms_label.appendChild(document.createTextNode(' '));
        terms_label.appendChild(terms_part1);
        terms_label.appendChild(document.createTextNode(' '));
        terms_label.appendChild(terms_link);
        terms_p.appendChild(terms_checkbox);
        terms_p.appendChild(terms_label);

        highres_link.appendChild(document.createTextNode(' '));
        highres_span.appendChild(document.createTextNode(' '));
        highres_link.appendChild(document.createTextNode(' '));
        highres_link.appendChild(highres_span);
        highres_p.appendChild(highres_link);
        lowres_link.appendChild(document.createTextNode(' '));
        lowres_span.appendChild(document.createTextNode(' '));
        lowres_link.appendChild(document.createTextNode(' '));
        lowres_link.appendChild(lowres_span);
        lowres_p.appendChild(lowres_link);

        win.appendChild(link);
        win.appendChild(header);
        win.appendChild(pic_p);
        win.appendChild(photographer);
        win.appendChild(terms_p);
        win.appendChild(highres_p);

        win.appendChild(lowres_p);

        win.appendChild(instructions);
    }
}
;


/* MEDIA GALLERIES */

addOnLoad(initVideoGalleries);

function initVideoGalleries() {
    if (Prototype && (ajaxObj = new Ajax.Request)) {

        // Check to see which DIVs are image galleries (if any)
        var DIVs = document.getElementsByTagName('DIV');
        var galleries = 0;
        var galleryType;
        for (var i = 0; i < DIVs.length; i++) {
            if (DIVs[i].className.match(/video_gallery/)) {
                galleries++;
                DIVs[i].id = 'video_gallery_' + galleries;
            }
        }

        // Loop through the links in each gallery and prepare them for AJAX integration
        for (var i = 0; i < galleries; i++) {
            regexp = /mediaid=([0-9]*)$/;
            gallery = $('video_gallery_' + (i + 1));
            links = gallery.getElementsByTagName('A');
            for (var k = 0; k < links.length; k++) {
                if (links[k].mediaid = regexp.exec(links[k].href)[1]) {
                    links[k].removeAttribute('href');
                    links[k].onclick = showVideoDownload;
                    links[k].onmouseout = ieHoverFix_out;
                    links[k].onmouseover = ieHoverFix_on;
                    links[k].picturepath = links[k].getElementsByTagName("img")[0].src;
                }
            }
        }

        // Create a DIV to be the Download Dialog
        if ($('video_gallery_1')) {
            var fakewin = document.createElement('DIV');
            var win = document.createElement('DIV');
            fakewin.id = 'video_gallery_fake_dl_window';
            win.id = 'video_gallery_dl_window';
            $('video_gallery_1').parentNode.insertBefore(fakewin, $('video_gallery_1'));
            $('video_gallery_1').parentNode.insertBefore(win, $('video_gallery_1'));
            resetVideoDlWindow();
        }
    }
}
;

function showVideoDownload(e) {
    if (win = $('video_gallery_dl_window')) {
        var ajax = new Ajax.Request(
                'videodownloadpopupxml.ahtml',
        {
            method: 'post',
            parameters: 'mediaid=' + this.mediaid,
            onSuccess: showVideoDownloadDone,
            onFailure: showVideoDownloadError
        });

        fakewin = $('video_gallery_fake_dl_window');

        while (win.hasChildNodes()) {
            win.removeChild(win.firstChild);
        }

        var loader_p = document.createElement('P');
        var loader_img = document.createElement('IMG');

        loader_p.id = 'gallery_dl_loader';

        loader_img.src = '/static/images/common/ajax_loader.gif';
        loader_p.appendChild(loader_img);
        win.appendChild(loader_p);

        var evt = e ? e : window.event;
        var posx = Event.pointerX(evt);
        var posy = Event.pointerY(evt);

        if (posx > 294) posx = 294;
        if (posy > 288) posy = 288;

        galleryWinPosX = posx - 100;
        galleryWinPosY = posy - 100;

        win.style.left = galleryWinPosX + 'px';
        fakewin.style.left = galleryWinPosX + 'px';
        win.style.top = galleryWinPosY + 'px';
        fakewin.style.top = galleryWinPosY + 'px';

        if (!win.className.match(/ show/)) {
            win.className += ' show';
            fakewin.className += ' show';
        }
    }
}
;

function hide_videoDownload() {
    if (win = $('video_gallery_dl_window')) {
        fakewin = $('video_gallery_fake_dl_window');
        if (win.className.match(/ show/)) {
            hideLoginPopup();
            hidePolicyPopup();
            win.className = win.className.replace(' show', '');
            fakewin.className = fakewin.className.replace(' show', '');
            resetVideoDlWindow();
        }
        if (win.className.match(/show/)) {
            hideLoginPopup();
            hidePolicyPopup();
            win.className = win.className.replace('show', '');
            fakewin.className = fakewin.className.replace('show', '');
            resetVideoDlWindow();
        }
    }
}
;


function showVideoDownloadDone(response) {
    resetVideoDlWindow();
    var header = $('videogallery_dl_header');
    var terms = $('videogallery_dl_terms');
    var terms_part1 = $('videogallery_dl_terms_part1');
    var terms_link = $('videoprivacy_policy_link');
    var instructions = $('videogallery_dl_instructions');
    var description = $('videogallery_dl_description');
    var videotag = $('gallery_dl_videotag');
    var downloads = $('gallery_dl_downloads');
    var ajaxResponse = Try.these(
            function() {
                return new DOMParser().parseFromString(response.responseText, 'text/xml');
            },
            function() {
                var xmldom = new ActiveXObject('Microsoft.XMLDOM');
                xmldom.loadXML(response.responseText);
                return xmldom;
            }
            );


    header.replaceChild(document.createTextNode(ajaxResponse.getElementsByTagName('header')[0].firstChild.nodeValue), header.firstChild);
    var descriptionElement = ajaxResponse.getElementsByTagName('video')[0].getElementsByTagName('description')[0].firstChild.nodeValue;
    if (descriptionElement != null && descriptionElement.trim() != '') {
        description.appendChild(document.createTextNode(ajaxResponse.getElementsByTagName('video')[0].getElementsByTagName('description')[0].firstChild.nodeValue));
        description.appendChild(document.createElement('BR'));
        description.style.display = 'block';
    }
    else if (descriptionElement != null) {
        description.style.display = 'none';
    }

    terms_part1.appendChild(document.createTextNode(ajaxResponse.getElementsByTagName('terms_part1')[0].firstChild.nodeValue.trim()));
    terms_link.appendChild(document.createTextNode(ajaxResponse.getElementsByTagName('terms_part2')[0].firstChild.nodeValue.trim()));

    instructions.replaceChild(document.createTextNode(ajaxResponse.getElementsByTagName('instructions')[0].firstChild.nodeValue), instructions.firstChild);

    if (DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision)) {
        var movieScriptTag = ajaxResponse.getElementsByTagName('flashmovieplayerscripttag')[0].firstChild.nodeValue.trim();
        var isMac = (navigator.appVersion.indexOf("Mac") != -1);
        if (isMac) {
            movieScriptTag = movieScriptTag.replace('fullscreen=1', 'fullscreen=0');
        }
        videotag.innerHTML = movieScriptTag;
    } else {
        videotag.appendChild(document.createElement('BR'));
        videotag.appendChild(document.createTextNode(ajaxResponse.getElementsByTagName('noflash_text')[0].firstChild.nodeValue));
        videotag.appendChild(document.createElement('BR'));
        var downloadFlashLink = document.createElement('A');
        downloadFlashLink.appendChild(document.createTextNode(ajaxResponse.getElementsByTagName('download_flash_text')[0].firstChild.nodeValue));
        downloadFlashLink.href = ajaxResponse.getElementsByTagName('download_flash_link_text')[0].firstChild.nodeValue;
        downloadFlashLink.target = '_blank'

        videotag.appendChild(downloadFlashLink);

    }

    var downloadsElement = ajaxResponse.getElementsByTagName('video')[0].getElementsByTagName('downloads')[0].getElementsByTagName('download');
    if (downloadsElement != null) {
        for (var i = 0; i < downloadsElement.length; i++) {
            var downloadLink = document.createElement('A');
            var downloadElement = downloadsElement[i];
            downloadLink.appendChild(document.createTextNode(downloadElement.getElementsByTagName('label')[0].firstChild.nodeValue));
            downloadLink.mediaDataId = downloadsElement[i].getElementsByTagName('mediadataid')[0].firstChild.nodeValue;
            downloadLink.linkto = 'javascript:showPressMediaLoginPopup("' + downloadsElement[i].getElementsByTagName('mediadataid')[0].firstChild.nodeValue + '");'
            var downloadLink_Span = document.createElement('SPAN');
            downloadLink_Span.appendChild(document.createTextNode(' (' + downloadElement.getElementsByTagName('size')[0].firstChild.nodeValue + ' MB)'));
            downloadLink.appendChild(downloadLink_Span);
            downloads.appendChild(downloadLink);
        }
    }
}
;

function resetVideoDlWindow() {
    if (win = $('video_gallery_dl_window')) {
        while (win.hasChildNodes()) {
            win.removeChild(win.firstChild);
        }

        var link = document.createElement('A');
        var header = document.createElement('H4');
        var videotag = document.createElement('P');
        var description = document.createElement('P');
        var terms_p = document.createElement('P');
        var terms_label = document.createElement('LABEL');
        var terms_checkbox = document.createElement('INPUT');
        var terms_part1 = document.createElement('SPAN');
        var terms_link = document.createElement('A');
        var instructions = document.createElement('P');
        var downloads = document.createElement('P');

        header.id = 'videogallery_dl_header';
        terms_p.id = 'videogallery_dl_terms';
        terms_part1.id = 'videogallery_dl_terms_part1';
        terms_link.id = 'videoprivacy_policy_link';
        instructions.id = 'videogallery_dl_instructions';
        videotag.id = 'gallery_dl_videotag';
        description.id = 'videogallery_dl_description';
        downloads.id = 'gallery_dl_downloads';

        videotag.className = 'gallery_dl_videotag';
        videotag.alt = '';
        link.appendChild(document.createTextNode('Close'));
        link.onclick = hide_videoDownload;
        link.href = '#';
        link.className = 'close_popup';
        header.appendChild(document.createTextNode(' '));
        videotag.appendChild(document.createTextNode(' '));
        instructions.appendChild(document.createTextNode(' '));
        downloads.appendChild(document.createTextNode(' '));
        terms_checkbox.onclick = allow_videoDownload;

        terms_checkbox.id = 'videogallery_dl_terms_checkbox';
        terms_checkbox.type = 'checkbox';
        terms_link.href = 'javascript:showPressImagePolicyPopup();';
        terms_label.appendChild(document.createTextNode(' '));
        terms_label.appendChild(terms_part1);
        terms_label.appendChild(document.createTextNode(' '));
        terms_label.appendChild(terms_link);
        terms_p.appendChild(terms_checkbox);
        terms_p.appendChild(terms_label);

        win.appendChild(link);
        win.appendChild(header);
        win.appendChild(videotag);
        win.appendChild(description);
        win.appendChild(instructions);
        win.appendChild(terms_p);
        win.appendChild(downloads);
    }
}
;

function showVideoDownloadError() {
    hide_imageDownload();
    alert('There was an error while loading the details for this video. Please try again later.');
}
;


function showPressMediaLoginPopup(mediaDataId) {
    if (Prototype && (ajaxObj = new Ajax.Request)) {
        if ($('video_gallery_dl_window') == null) {
            ppPosx = 725;
            ppPosx = 460;
        }
        var ajax = new Ajax.Request(
                'medialogin.ahtml',
        {
            method: 'post',
            parameters: 'mediadataid=' + mediaDataId,
            onSuccess: showLoginPopupDone,
            onFailure: showPressImagePolicyPopupError
        });
    }
}
;

function showLoginPopupDone(response) {
    fakePPwin = createLoginPopup();
    fakePPwin.innerHTML = response.responseText;
    fakePPwin.style.visibility = 'visible';
    $('login_fakewin_back').style.visibility = 'visible';
}
;

//Create a DIV to be the Privacy Policy Popup
function createLoginPopup() {
    var ppWinBack;
    var ppWin;

    //Window does not exist - create one.
    if ($('login_fakewin') == null || $('login_fakewin_back') == null) {
        ppWinBack = document.createElement('DIV');
        ppWinBack.id = 'login_fakewin_back'
        ppWin = document.createElement('DIV');
        ppWin.id = 'login_fakewin';

        //Window does already exist - get the old one.
    } else {
        ppWinBack = $('login_fakewin_back');
        ppWin = $('login_fakewin');
    }

    //Window is on top of the gallery_dl_window, set window position relative to the parent
    if ($('video_gallery_dl_window') != null && galleryWinPosX && galleryWinPosY) {
        ppWinBack.style.left = 'auto';
        ppWin.style.left = 'auto';
        ppWinBack.style.top = 'auto';
        ppWin.style.top = 'auto';

        //Set window position based on mouse coordinates
    } else {
        ppWinBack.style.left = ppPosX + 'px';
        ppWin.style.left = ppPosX + 'px';
        ppWinBack.style.top = ppPosY + 'px';
        ppWin.style.top = ppPosY + 'px';
    }

    //
    hideSelectBoxes();
    //It is not possible to insert this new element under its parent bacause that
    //might be a <label> which causes problems with IE 6.0. Instead we append it to content.
    $('content').appendChild(ppWinBack);
    $('content').appendChild(ppWin);
    return ppWin;
}
;

function loginUser(form) {
    if (Ajax.getTransport()) {
        var ajax = new Ajax.Request(
                'medialogin.ahtml',
        {
            method: 'post',
            parameters: Form.serialize(document.forms[form]),
            onSuccess: loginUser_done,
            onFailure: loginUser_done
        });
    }
}
;

function loginUser_done(response) {
    var loginResult = response.responseText.trim();
    if (loginResult != 'null') {
        redirect(loginResult);
        hideLoginPopup();
    } else {
        showError();
        clearPasswordField();
        document.getElementById("username").select();
    }
}
;

function loginUser_failed(response) {
    alert('Login Failed');
}
;

function hideLoginPopup() {
    if (fakeLoginWin = $('login_fakewin')) {
        fakeLoginWin.parentNode.removeChild(fakeLoginWin);
    }
    if (fakeLoginWinBack = $('login_fakewin_back')) {
        fakeLoginWinBack.parentNode.removeChild(fakeLoginWinBack);
    }
    showSelectBoxes();
}
;

function showError() {
    var browserType;

    if (document.layers) {
        browserType = "nn4"
    }
    if (document.all) {
        browserType = "ie"
    }
    if (window.navigator.userAgent.toLowerCase().match("gecko")) {
        browserType = "gecko"
    }
    if (browserType == "gecko")
        document.poppedLayer =
                eval('document.getElementById("errorMessage")');
    else if (browserType == "ie")
        document.poppedLayer =
                eval('document.getElementById("errorMessage")');
    else
        document.poppedLayer =
                eval('document.layers["errorMessage"]');
    document.poppedLayer.style.visibility = "visible";
}
;

function clearPasswordField() {
    document.getElementById("password").value = "";
}
;

function redirect(url) {
    window.parent.location = url;
}
;


function allow_videoDownload() {

    var download_tag = $('gallery_dl_downloads');
    if (download_tag != null) {
        var download_links = download_tag.getElementsByTagName("A");
        setVideoDownloadButtonStatus(download_links);
    }

    download_tag = $('gallery_dl_download_page');
    if (download_tag != null) {
        var download_links = download_tag.getElementsByTagName("A");
        setVideoDownloadButtonStatus(download_links);
    }
}
;

function setDownloadButtonStatus(download_links) {
    var terms_checkbox = $('gallery_dl_terms_checkbox');
    for (var i = 0; i < download_links.length; i++) {
        if (terms_checkbox.checked) {
            download_links[i].className = 'active';
            download_links[i].setAttribute('onmousedown', 'trackElementEvent(Gallery_Terms_Check, \'Gallery\')');
            download_links[i].href = download_links[i].linkto;
        } else {
            download_links[i].className = '';
            download_links[i].removeAttribute('onmousedown');
            download_links[i].linkto = download_links[i].href;
            download_links[i].removeAttribute('href');
            hideLoginPopup();
        }
    }
}
;

function setVideoDownloadButtonStatus(download_links) {
    var terms_checkbox = $('videogallery_dl_terms_checkbox');
    for (var i = 0; i < download_links.length; i++) {
        if (terms_checkbox.checked) {
            download_links[i].className = 'active';
            download_links[i].setAttribute('onmousedown', 'trackElementEvent(Video_Gallery_Terms_Check, \'Gallery\')');
            download_links[i].href = download_links[i].linkto;
        } else {
            download_links[i].className = '';
            download_links[i].removeAttribute('onmousedown');
            download_links[i].linkto = download_links[i].href;
            download_links[i].removeAttribute('href');
            hideLoginPopup();
        }
    }
}
;

function setLinktoFromHref() {
    var download_tag = $('gallery_dl_download_page');
    if (download_tag != null) {
        var download_links = download_tag.getElementsByTagName("A");
        for (var i = 0; i < download_links.length; i++) {
            download_links[i].linkto = download_links[i].href;
            download_links[i].removeAttribute('href');
        }
    }
}
;

function showExtraCards() {
    document.getElementById('extracard').className = "extracard_container_show";
    document.getElementById("showhide").className = "hide_extracards";
}
function toggleExtraCards() {
    if (document.getElementById('extracard').className == "extracard_container") {
        document.getElementById('extracard').className = "extracard_container_show";
        document.getElementById("showhide").className = "hide_extracards";
    }
    else if (document.getElementById('extracard').className == "extracard_container_show") {
        document.getElementById('extracard').className = "extracard_container";
        document.getElementById("showhide").className = "show_extracards";
    }
}

/*
 Handles Omniture tracking for MoviePlayer
 */
function trackFlashActivity(name) {

    // specify which properties and events that should be sent to Omniture...
    //s.linkTrackVars="prop1,prop5,prop44,events";
    //s.linkTrackEvents="event5";

    // track as "other" link
    // ends up in the report under "Custom Links"
    // first object/flag results in no delay beeing used before sending tracking request to Omniture
    s.tl(true, 'o', name);
}

/* Core Metrics tracking functions */


/* Core */
/**
 * Tracking pageviews in flash 
 * @param pageId - Uniquely identifies the given ‘page’ in Coremetrics
 * @param pageCategory - Category ID for the leaf node to which this page belongs
 * @param searchTerm - Onsite search term used to get to the Search Results page
 * @param searchResults - Number of results returned by the keyword search
 * @param attributeString - Up to 15 “-_-“ delimited ‘attribute’ values accessible in Explore reporting
 */
function trackFlashPageView(pageId, pageCategory, searchTerm, searchResults, attributeString){
    void(cmCreatePageviewTag(pageId, pageCategory, searchTerm, searchResults, attributeString));
}
/**
 * The Element tag is used to track intra-page content in Coremetrics Online Analytics.
 * @param elementId
 * @param elementCategory
 * @param attributeString
 */
function trackElementEvent(elementId, elementCategory, attributeString){
    void(cmCreateElementTag(elementId, elementCategory, attributeString));    
}
/**
 * Tracking of general non-commerce conversion events
 * @param eventId - A unique identifier for the type of conversion
 * @param actionType - A value of “1” or “2” depending upon whether a conversion initiation or a successful conversion completion is generated
 * @param categoryId - Allows grouping of event IDs into categories
 * @param points - A point value used in establishing an arbitrary “value” for a conversion
 * @param attributeString - Up to 15 “-_-“ delimited ‘attribute’ values accessible in Explore reporting
 */
function trackConversionEvent(eventId, actionType, categoryId, points, attributeString){
    void(cmCreateConversionEventTag(eventId, actionType, categoryId, points, attributeString));
}

/* Convenience */

/* Track an event in the quiz */
function trackQuiz(eventName){
    void(trackFlashPageView(""+eventName, "corp:quiz", null, null));
    
}

function getVideoParameterString(event){
    //This is the fantastic format requested by the tracking API to specifically send data on parameter #13
    return "-_--_--_--_--_--_--_--_--_--_--_--_-" + event;
}

function trackMoviePlayer(movieName, event){
    void(trackElementEvent(movieName, "corp:moviePlayer", getVideoParameterString(event)));
}



