﻿function UpdateInstallPrice(lblInstallPriceClientId, installPrice, txtQtyClientId, evt)
{  
        
        var qtyReqd = parseInt(document.getElementById(txtQtyClientId).value);        
        if(isNaN(qtyReqd))
        {
            qtyReqd = 1;
        }
        var totalInstallPrice = qtyReqd * installPrice;            
        document.getElementById(lblInstallPriceClientId).innerHTML = 'Install for me(£' + totalInstallPrice + '.00)';
}

function CheckNumericQty(txtQtyClientId, evt)
{
    var charCode = (evt.which) ? evt.which : event.keyCode
    
    if (charCode > 31 && (charCode < 48 || charCode > 57))
    {       
        return false;
    }
    else
    {
        return true;
    }
}

$(document).ready(function() {
    $(".thumb_change_link").click(function(evt) {
        var tgt = $(evt.target);
        var orig = tgt.attr("src").replace(/png/i, "jpg");
        var src = orig.replace(/Gallery/gi, "Main");
        var hrf = orig.replace(/Gallery/gi, "Full");
        $('.main_image').attr("alt", tgt.attr("alt"));
        $(".main_image").attr("src", src);
        $(".lb_link").attr("href", hrf);
        return false;
    });

    //Switch on the first variant checkbox if required
    SelectAVariant();

    //Set the left and right product div to same size.
    var difference = Math.abs($('#product_left').height() - $('#product_right').height());
    if ($('#product_left').height() < $('#product_right').height()) {
        $('#galleryAndAttributes').css('height', $('#galleryAndAttributes').height() + difference);
    }
    else {
        $('#tab_body').css('height', $('#tab_body').height() + difference);
    }


    $(".lb_link").click(function(evt) {
        $(evt.target).lightbox({ start: true, events: false, ie6_support: true, ie6_upgrade: false }); return false;
    });

    $(".input_email input").click(function(evt) {
        $(evt.target).val("");
    });

    $(".order_bar_oos .input_quantity input").click(function(evt) {
        $(evt.target).val("");
    });

    $(".thumb-prev").click(function(evt) {
        var picViewer = $(evt.target).siblings('.carousel-container').find('.carousel');
        if (picViewer.children().size() > 4) {
            picViewer.find('a:first').clone(true).appendTo(picViewer);

            var firstPic = picViewer.find('a:first');
            firstPic.animate({ marginLeft: -98 }, 500, null,
            function() {
                firstPic.remove();
            });
        }
        return false;
    });

    $(".thumb-next").click(function(evt) {
        var picViewer = $(evt.target).siblings('.carousel-container').find('.carousel');
        if (picViewer.children().size() > 4) {
            lastPic = picViewer.find('a:last')
            lastPic.clone(true).prependTo(picViewer);

            var firstPic = picViewer.find('a:first');
            firstPic.css('marginLeft', -98);
            firstPic.animate({ marginLeft: 0 }, 500, null,
            function() {
                lastPic.remove();
            });
        }
        return false;
    });

    $(".radio").click(function(evt) {
        //Get a handle on our selected parent variant
        var tgt = $(evt.target).parent().parent();
        checkStock(tgt.find('img:first').attr('src'), tgt.find("input[id$='hidUnit']").val(), tgt.find("input[id$='hidOrderMultiple']").val());

        //Can the customer see a choices drop down
        if ($('.MARComboTop').val() != null) {
            //yep, so clear em down
            clearChoices();
        }

    });

    function clearChoices() {
        
        $('.MARComboTop').parent().find('.choice').each(function(i, tgt) {
            $(tgt).find('input:first').attr('checked', false);
        });
    }


    function checkStock(imgSrc, salesUnit, orderQty) {
        var patt = new RegExp("In_Stock_Order");
        if (patt.test(imgSrc)) {
            //In Stock            
            $('.order_bar_oos').css('display', 'none');
            $('.order_bar').css('display', 'block');
            $('.OrderQty').val(orderQty);
        }
        else {
            //OOS
            $('.order_bar').css('display', 'none');
            $('.order_bar_oos').css('display', 'block');
            $('.input_email input').val('Email me when in stock');
            $('.order_bar_oos .input_quantity input').val('Qty reqd');
        }

        $('.label_salesUnit').html(salesUnit);
    }

    function SelectAVariant() {
        //Check if any variant radio buttons are selected if not it pick the first one
        var checkedVariant;
        //Loop through all variants
        $('.variant').each(function(i, tgt) {
            if ($(tgt).find('input:first').attr('checked') == true) {
                checkedVariant = $(tgt);
            }
        });

        if (checkedVariant == null) {
            //no variants selected so switch on first radio button            
            checkedVariant = $('.variant').eq(0);
            checkedVariant.find('input:first').attr('checked', 'checked');
        }

        //Finally, check stock on relevant variant and display correct panel
        checkStock(checkedVariant.find('img:first').attr('src'), checkedVariant.find("input[id$='hidUnit']").val(), checkedVariant.find("input[id$='hidOrderMultiple']").val());

    }

    //Combo Image Clicked
    $(".MARComboTop").click(function(evt) {
        //Get a handle on the .ComboMiddle div of the button clicked
        var tgt = $(this).parent().children(".MARComboBody");
        if ($(tgt).is(":visible")) {
            $(tgt).animate({ opacity: "hide", height: "hide" }, "slow");
        }
        else {
            $(tgt).animate({ opacity: "show", height: "show" }, "slow");
        }

        return false;
    });

});

function Add_Click(shopId, productItemId, productName, installId, basketURL, txtQtyClientId, chkIncInstClientId, aAddButtonClientId) {
    //Function that checks through all product variants to check one is selected
    //then it looks to see if the variant has any choices i.e colour
    //If it has then it checks to see if one is selected otherwise it prevents a postback
    var objAddButton = document.getElementById(aAddButtonClientId); //get add button anchor    
    var selectedVariant;
    var retType = false;
    var choicesDesc = '';  //Hold description of all choices made (if applicable)
    
    //Loop through all variant radio buttons to find the one that is selected
    $('.variant').each(function(i, tgt) 
    {
        if ($(tgt).find('input:first').attr('checked') == true) 
        {
            selectedVariant = $(tgt);
        }
    });
  

    //If the selected variant is a sample, check that the sample limit has not been
    //breached
    var desc = (selectedVariant.find('.variantDesc').text()).match('Sample');
    if( desc == 'Sample' || desc == 'sample' ) {
        var basketSamps =  $("input[id$='hidBasketSampleQty']").val();
        var sampsLimit = $("input[id$='hidSampleLimit']").val();
        if (basketSamps >= sampsLimit) {            
            alert('Sorry, no more than ' + sampsLimit + ' free samples are available.\r\nIf you require more than ' + sampsLimit + ' samples a delivery charge may apply.\r\nPlease contact our Customer services team for more details.');
            return false;            
        }
    }    
    
    //Now see if the variant has any choices
    if ($('.MARComboTop').val() == null) {        
        //Nope, so post back
        retType = true;
    }
    else {        
        //We have choices big boy! lets loop throught them to make sure one is checked
        $('.MARComboTop').parent().find('.choice').each(function(i, tgt) {
            if ($(tgt).find('input:first').attr('checked') == true) {
                //One is checked so let the post back commence
                retType = true;
                //Also Add Selected choice to variable for postback                
                choicesDesc = choicesDesc + '-' + $(tgt).find('.choiceDesc').text();
            }
        });
    }
    
    //No variant is selected, or check box ticked so you are not going to the
    //ball (on the server)
    if (retType == false) {
        alert('You need to ' + $('.MARComboTop').html() + ' from the drop down list\r\nbefore you can add to the basket.');    
        return retType;
    }
    else {
        
        //Redirect to basket url. This function is a Google Analytics function
        //that passes client cookie info to basket screen.  It also does the redirect.
        //Get selected variant item id
        desc = selectedVariant.find("input[id$='hidVariantItemId']").val();
        //Get qty
        var qtyReqd = document.getElementById(txtQtyClientId).value;

        //If Install is available, but not ticked, blank out installid (this will prevent install being added)        
        if (document.getElementById(chkIncInstClientId) != null && document.getElementById(chkIncInstClientId).checked == false) { installId = ''; }

        //var googURL = pageTracker._getLinkerUrl(myURI, window);
        //Build and set url for add to basket anchor
        //objAddButton.href = basketURL + '/basket.aspx?ShopId=' + shopId + '&VarId=' + desc + '&PrdId=' + productItemId + '&qty=' + qtyReqd + '&PrdName=' + productName + '&ChoiDesc=' + choicesDesc + '&installId=' + installId + '&action=add';
        
        
        var URLv1 = basketURL + '/basket.aspx?ShopId=' + shopId + '&VarId=' + desc + '&PrdId=' + productItemId + '&qty=' + qtyReqd + '&PrdName=' + productName + '&ChoiDesc=' + choicesDesc + '&installId=' + installId + '&action=add';

        objAddButton.href = GoogleAnalyticsCookieAppend(URLv1);
        
        //Call GoogAnalytics function passing in href
        pageTracker._link(objAddButton.href);
        return false;
    }

}


function GoogleAnalyticsCookieAppend(uri) 
{
    //Get location of the start of the querystring
    var queryStringIndex = uri.indexOf('?');
    
    //Extract the querystring from the URL
    var queryString = (queryStringIndex == -1) ? "" : uri.slice(queryStringIndex + 1);

    //Now just get the URL
    var myURI = (queryStringIndex == -1) ? uri : uri.slice(0, queryStringIndex);
    
    //Use the Google Analytics function to get GA variables
    var c = pageTracker._getLinkerUrl(myURI, window);
    
    //Explicitly check in case GA is using #
    c = c.replace("#", "?");    
    
    //reappend querystring variables
    c += "&" + queryString;
    
    return c;
}

function SetUniqueRadioButton(nameregex, current)
{
   re = new RegExp(nameregex);
   for(i = 0; i < document.forms[0].elements.length; i++)
   {
      elm = document.forms[0].elements[i]
      if (elm.type == 'radio')
      {                    
         if (re.test(elm.name))
         {            
            elm.checked = false;
         }
      }
  }
   current.checked = true;
}

function SetUniqueCheckBox(nameregex, current) {

    var selectedVariant;

    //Loop through all variant radio buttons to find the one that is selected
    $('.variant').each(function(i, tgt) 
    {
        if ($(tgt).find('input:first').attr('checked') == true) 
        {
            selectedVariant = $(tgt).find("input[id$='hidMaxChoices']").val();
        }
    });

    if (selectedVariant != 99) {
        //It's open season you can have as many choices as you like
        //To Do, incorporate the number of MaxChoices into logic to limit selection
        re = new RegExp(nameregex);
        for (i = 0; i < document.forms[0].elements.length; i++) {
            elm = document.forms[0].elements[i]
            //alert(elm.type);
            if (elm.type == 'checkbox') {

                if (re.test(elm.name)) {
                    elm.checked = false;
                }
            }
        }
        current.checked = true;
    }
}









