/* ****************************************** CONTENT QUERYING ****************************************** */

function querySubTopicContent(contentUri, parentContentUri) {
    //check to see if the function exists, if so then set link to the contenturi
    if (setEmailFriendLink) {
        setEmailFriendLink(contentUri, parentContentUri);
    }

    contentService.getSubTopicContentByContentURI(contentUri, parentContentUri, updateSubTopicPageContent);
}

function updateSubTopicPageContent(results) {

    var contentAsString = results[0];
    var title = results[1];
    var subtopicNavigationHTML = results[2];
    var rightModuleContentArray = results[3];
    var leftModuleContentArray = results[4];
    var backToTopMessage = results[5];

    var sectionTitle = document.getElementById("top");
    var subtopicContent = document.getElementById("centerColumn");
    var subtopicNavigation = document.getElementById("subtopicLIs");
    var rightModuleContentArea = document.getElementById("rightModulesContentArea");
    var leftModuleContentArea = document.getElementById("leftModulesContentArea");

    if (rightModuleContentArea != null) {
        rightModuleContentArea.innerHTML = "";
    }
    if (leftModuleContentArea != null) {
        leftModuleContentArea.innerHTML = "";
    }

    for (var i = 0; i < rightModuleContentArray.length; i++) {
        if (rightModuleContentArea != null) {
            rightModuleContentArea.innerHTML = rightModuleContentArea.innerHTML + rightModuleContentArray[i];
        }
    }

    for (var j = 0; j < leftModuleContentArray.length; j++) {
        if (leftModuleContentArea != null) {
            leftModuleContentArea.innerHTML = leftModuleContentArea.innerHTML + leftModuleContentArray[j];
        }
    }

    subtopicContent.innerHTML = contentAsString + "<a href='#top' class='backTop'>" + backToTopMessage + "</a>";

    if (sectionTitle != null) {
        sectionTitle.innerHTML = title;
    }

    subtopicNavigation.innerHTML = subtopicNavigationHTML;

    roundedCorners();
    toolTip();
    positionRetrieverPopup();
    applyNewsletterSignupBoxClickAction();
    applyRetrieverCloseClickAction();
    
     //Init lightbox links on sub-topic change
    tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;

}

function displayProduct(productId) {
    contentService.getFeaturedProductContentByObjectName(productId, displayFeaturedProductContent);
}

function displayFeaturedProductContent(results) {
    var featuredProductContent = document.getElementById("featuredProductContent");
    featuredProductContent.innerHTML = results;
}

/* ****************************************** EMAIL A FRIEND ****************************************** */

$(document).ready(function() {

    $("#emailBoxContent a.submit").click(function() {
        //alert('Submit 1');
        $(this).parents().filter("form").trigger("submit");
        //alert('Submit 2');
    });

    $("#emailBoxContent a.close").click(function() {
        closeEmailBox();
        var validator = $("#emailAFriendForm").validate();
        validator.resetForm();
    });
});

//static global variable to store the link used for email friend.  It can change by clicking subheadings in the page.
var EMAIL_FRIEND_LINK;
var EMAIL_FRIEND_PARENT_URI;

function emailAFriend() {

    //alert('emailAFriend()');
    var fromName = ''; //document.getElementById('fromName');
    var fromEmail = document.getElementById('senderEmail').value;

    var toName = ''; //document.getElementById('toName');
    var toEmail = document.getElementById('receiverEmail').value;

    var subject = document.getElementById('emailSubject').value;
    var message = document.getElementById('emailMessage').value;
    var copyMe = document.getElementById('emailCopyMe').checked;


    var link = document.getElementById('emailLink').value;

    //alert('link: ' + link + '\n' + 'EMAIL_FRIEND_LINK: ' + EMAIL_FRIEND_LINK + ' \n' + 'EMAIL_FRIEND_PARENT_URI: ' + EMAIL_FRIEND_PARENT_URI);

    if (EMAIL_FRIEND_LINK && EMAIL_FRIEND_PARENT_URI) {
        link = link.replace(EMAIL_FRIEND_PARENT_URI, EMAIL_FRIEND_LINK);
    }

    //alert('link: ' + link + '\n' + 'EMAIL_FRIEND_LINK: ' + EMAIL_FRIEND_LINK + ' \n' + 'EMAIL_FRIEND_PARENT_URI: ' + EMAIL_FRIEND_PARENT_URI);

    //alert('Copy me: ' +  copyMe + '\ncopyMeBoolean:  ' + copyMeBoolean + '\ncopyMeBoolean (alt): ' + (copyMe == '1'));

    var subtopic = document.getElementById('emailSubtopic').value;
    var description = document.getElementById('emailDescription').value;

    trackEvent('EmailFriend', 'COMPLETE');    
    
    emailAFriendService.emailAFriend(fromName, fromEmail, toName, toEmail, subject, message, link, subtopic, description, copyMe, closeEmailBox);
}

function confirmEmail() {
    closeEmailBox();
    $('#emailConfirm').fadeIn();
}

function closeEmailBox() {
    $('#emailBox').fadeOut();
    var validator = $("#emailAFriendForm").validate();
    validator.resetForm();
    $.emailFriendValidator.resetForm();
    $("#emailAFriendForm").resetForm();
    $('#emailConfirm').fadeIn();
}

/**
 * Used to set global variables used to create email friend link.
 * @param uri
 * @param parentUri
 */
function setEmailFriendLink(uri, parentUri) {
    EMAIL_FRIEND_LINK = uri;
    EMAIL_FRIEND_PARENT_URI = parentUri;
}

/* ****************************************** UTILITY FUNCTIONS ****************************************** */

/** Standard popup window open
 * The first parameter will be the new URL.
 * Subsequent parameters will be (if supplied) the width and height.
 * If not specified the width and height will be 500 and 200 respectively.
 */
function openWin() {
    var url, width = 500, height = 200, menu = "";
    args = arguments;
    url = args[0];
    if (args.length > 1) {
        width = args[1];
    }
    if (args.length > 2) {
        height = args[2];
    }
    if (args.length > 3) {
        if (args[3]) {
            menu = ",menubar=yes,toolbar=yes";
        }
    }
    var newwin = window.open(url, 'newWin' + Math.floor(Math.random() * 1000), 'width=' + width + ',height=' + height + ',scrollbars,resizable' + menu);
}

function replaceValueOnInputElement(elementObj, originalValueToReplace) {

    var inputValue = elementObj.value;

    if (inputValue == originalValueToReplace) {
        elementObj.value = '';
    }

    return false;
}

/* ****************************************** ONLINE ORDERING ****************************************** */

function addItemToCartByProductCodeIncrementQuantityForExistingCallback(resultArray) {

    var productCode = resultArray[0];
    var itemsInCart = resultArray[1];

    var cartLink = document.getElementById("cartLink");
    cartLink.style.display = "inline";

    updateHeaderCartQty(itemsInCart);
    updateQuantityValues('qtyval', itemsInCart);
    totalCartItems = itemsInCart;

    //jQuery(function($) {$('#addToCart' + productCode).hide();});
}

function updateHeaderCartQty(qty) {
    var cartQtyHTML = document.getElementById("cartqty");
    cartQtyHTML.innerHTML = "(" + qty + ")";
}

function updateQtyByProductCodeCallback(resultArray) {

    var productCode = resultArray[0];
    var itemsInCart = resultArray[1];

    updateHeaderCartQty(itemsInCart);
    updateQuantityValues('qtyval', itemsInCart);
    //This is kind of a hack until I can find a better way
    selectOption('quantity' + productCode, itemsInCart - 1);
    hideBox('#qtychange' + productCode);

}

function selectOption(elementId, num) {
    var selObj = document.getElementById(elementId);
    selObj.selectedIndex = num;
}

function hideBox(code) {
    jQuery(function($) {$(code).hide();});
}

function updateQuantityValues(idVal, qty) {

    var anyIdElements = new Array();
    anyIdElements.length = 0;

    getElementsByIdName(anyIdElements, idVal, document.body);

    for (var i = 0; i < anyIdElements.length; i++) {
        //Update the element
        anyIdElements[i].innerHTML = qty;
    }
}

function getElementsByIdName(anyIdElements, idName, obj) {
    if (obj.id != undefined && obj.id.match(idName)) {
        anyIdElements[anyIdElements.length] = obj;
    }

    for (var i = 0; i < obj.childNodes.length; i++) {
        getElementsByIdName(anyIdElements, idName, obj.childNodes[i]);
    }
}

/* ##################################### FONT SIZE CHANGER ############################### */

function setFontSizeFromCookie() {
    var fontSize = $.cookie('font-size');
    //alert('Font Size: ' + fontSize + ' null? ' + (fontSize != null) + ' blank? ' + (fontSize != ''));
    if (fontSize != null) {
        //alert('Font Size: settign to ' + fontSize );
        var currentFontSize = $('body').css('font-size');
        //alert('Before: ' + currentFontSize);

        var fontSizeNum = parseFloat(fontSize, 10);

        $('body').css('font-size', fontSizeNum);

        currentFontSize = $('body').css('font-size');
        //alert('After: ' + currentFontSize);
    }
}


/* ##################################### NEWSLETTER SIGNUP ############################### */


function submitNewsletterUpdate()
{
    var userId = document.getElementById('userId').value;
    var newsletterInd = document.getElementById('newsletterInd').checked;

    if(newsletterInd)
    {
        userProfileService.subscribeToNewsletter();
    }
    else
    {
        userProfileService.unSubscribeToNewsletter();
    }
    $('#newsletterSignupBox').fadeOut();

    if(newsletterInd)
    {
        $('#newsletterSubscribeBox').fadeIn();
    }
    else
    {
        $('#newsletterUnsubscribeBox').fadeIn();
    }
}


function setProductRegisterHref(id, test, loc, defaultLoc)
{
    //alert('id: ' + id + ", test: " + test + ", loc: "+ loc + ", default: " + defaultLoc + " test=" + (test != '-1'));
    if(test != '-1')
    {
        $('#' + id).attr("href", loc);
    }
    else
    {
        $('#' + id).attr("href", defaultLoc);
    }
    //alert($('#' + id).attr("href"));
}


function externalLink(url)
{
    openWin(url,'800','600');
    _gaq.push(['siteTracker._trackPageview', url]);

    $("#TB_closeWindowButton").click();
}

function externalLinkWithiCrossing(url, iCrossing)
{
    openWin(url,'800','600');
    pTag(iCrossing);
    _gaq.push(['siteTracker._trackPageview', url]);

    var wboIdTransfo = null;

    if (iCrossing == 'https://cc.gbppc.com/ct/849/x.gif?cid=[]') {
        // Purchase Meter Site Exit
        wboIdTransfo = 9334;
    } else if (iCrossing == 'https://cc.gbppc.com/ct/850/x.gif?cid=[]') {
        // Purchase Cassette Site Exit
        wboIdTransfo = 9335;
    }

    if (wboIdTransfo != null) {
        executeConversionTag(wboIdTransfo);
    }

    $("#TB_closeWindowButton").click();
}



/*******  REFERENCE CODE UPDATES     ********/
function updateReferenceCodeCookie(newCode) {

    var refCode = $.cookie('campaignTracking');
    if(refCode != null){
        refCode = refCode + "," + newCode;
    }
    else{
        refCode = newCode;
    }
    
    refCode = trimReferenceCode(refCode);
                
    $.cookie('campaignTracking', refCode, { expires: 365, path: '/'});
    
}

function setReferenceCode() {
    var refCode = $.cookie('campaignTracking');
    if(refCode != null){
        refCode = trimReferenceCode(refCode);
        
        $("#refCode").val(refCode);
        $.cookie('campaignTracking', refCode, { expires: 365, path: '/'});
    }    
}


function trimReferenceCode(code)    {
    var i = code.indexOf(",");

//    alert('initial code: ' + code);
//    alert('initial code.length: ' + code.length);    
//    alert('comma at: ' + i);
        
    while( (code.length > 50) && (i > -1)) {
        
        if(i > -1)  {
            code = code.substr(i+1);            
        }

        i = code.indexOf(",");
                
//        alert('code: ' + code);
//        alert('code.length: ' + code.length);
//        alert('comma at: ' + i);
    }
    
    if(code.length > 50)    {
        code = code.substr(0, 50);
    }
    
//    alert('final code: ' + code);
//    alert('final code.length: ' + code.length);
    return code;
}    


//iCrossing functions
function pTag( pURLString){      
    var pTagHTML = pURLString;
    pImage = new Image();
    if (document.images){
        var Now = new Date();
        pImage.src = pTagHTML+"&nw="+ Now.getTime();
    } else {
        pTagHTML = '<I' + 'MG BORDER=\"0\" NAME=\"ptag\" WIDTH=\"1\" HEIGHT=\"1\" SRC=\"' + pTagHTML + ' \" >' ;
        document.write( pTagHTML );
    }
    return pTagHTML;
}


function mobileMicrositeAsReferrerTracking() {
    if (document.referrer.indexOf('/microsites/mobile') != -1) {
        // the visitor is coming from the mobile microsite

        var wboIdTransfo, audience;

        if (document.URL.indexOf('mobilebuyonlinetab.html') != -1) {
            // the visitor clicked on the "Buy Online" link in the microsite to get here
            wboIdTransfo = 9341;
            loadAudienceTag('mobile', 'buyonline');
        } else {
            // the visitor clicked on the "Learn More" link in the microsite to get here
            wboIdTransfo = 9342;
            loadAudienceTag('mobile', 'learnmore');
        }

        executeConversionTag(wboIdTransfo);
    }
}

function loadAudienceTag(section, subsection) {
    $('body').append('<img src="//rochediagnostics.solution.weborama.fr/fcgi-bin/comptage_wreport.fcgi?WRP_ID=449903&WRP_SECTION=' + section + '&WRP_SUBSECTION=' + subsection + '" border="0" width="1" height="1" alt=""/>')
}

function executeConversionTag(wboIdTransfo) {
    $.getScript('https://ssl.weborama.fr/wbo_performance.js', function() {
        WBO_AMOUNT="0.0"; /* <== set here the command amount */
        WBO_CLIENT="";     /* <== set here your client id */
        WBO_INVOICE="";     /* <== set here your bill id */
        WBO_NUM_ITEMS=1; /* <== set here the number of item */
        WBO_POST_VALIDATION=0; /* <== set to 1 if need backoffice validation */

        if (webo_performance) {
            transfo = new performanceTransfo(SITE=449903, WBO_ID_TRANSFO=wboIdTransfo);
            transfo.setAmount(WBO_AMOUNT);
            transfo.setClient(WBO_CLIENT);
            transfo.setId(WBO_INVOICE);
            transfo.setQuantity(WBO_NUM_ITEMS);
            transfo.setPostValidation(WBO_POST_VALIDATION);
            transfo.setHost("rochediagnostics.solution.weborama.fr");

            /* == Optional parameters == */
            //~optional parameters~
            /* == Type parameters == */
            /* == Free parameters == */
            transfo.execute();
        }
    });
}
