﻿var baseImagePreloadUrl = '';

$(function(){

    baseImagePreloadUrl = $('#img0').attr('src');
    baseImagePreloadUrl = baseImagePreloadUrl.substring(0, baseImagePreloadUrl.lastIndexOf('/') + 1);

    var firstColour = true;

    $('input[type=hidden][id$=ImageData]').each(function(){
        
        var imgdata = $(this).val().split('|');
        
        var firstLargeImageId = imgdata[0].split('~')[1];

        // Preload the first large image for each colour
        var preload = new Image();
        preload.src = baseImagePreloadUrl + firstLargeImageId + '.jpg';

        // And the other large images for the first colour, and all the thumbnails for every colour
        for(var x=0; x<imgdata.length; x++)
        {
            imgId = imgdata[x].split('~')[1];

            if(firstColour)
            {
                var preload3 = new Image();
                preload3.src = baseImagePreloadUrl + imgId + '.jpg';
            }

            var preload2 = new Image();
            preload2.src = baseImagePreloadUrl.replace(/\/plge\//gi, '/pthumb/') + imgId + '.jpg';
        }

        firstColour = false;

    });

    $('.productthumbl img, .productthumb img, .productthumbright img').bind('click', function() {

        $('#img0').attr('src', $(this).attr('src').replace(/\/pthumb\//gi, '/plge/'));
        $('#img0').parent().attr('href', $(this).attr('src').replace(/\/pthumb\//gi, '/pxlge/'));
        $('#ImageIndex').attr('value', parseInt($(this).attr('id').substring(3), 10));
    });

    // Add the item to basket, then show the recommendation/continue  window
    $('.stocktable a[href^=stockcheck], .stocktable-double a[href^=stockcheck]').bind('click', function() {
        
        $('#stockcheck').css('width', 720);
        $('#stockcheck #pad').html('<div id="stockcheckprogress">&nbsp;</div>');
        $('#stockcheck').center();
        $('#stockcheck').show();

        $('#focuser').css('height', $('body').height() + 10);
        $('#focuser').addClass('darkenBackground');

        $.get($(this).attr('href').replace(/stockcheck/gi, 'ajaxstockcheck'), function(data) {
            
            $('#stockcheck #pad').html(data);
        });

        return false;

    });
    
    $('#deliverypopuplink').bind('click', function() {
        $('#iframecontent').css('height', 530);
        $('#iframecontent').center();
        var html = "<div id=\"iframeheader\"><p><a href=\"#\" onclick=\"$('#focuser').removeClass(); $('#focuser').css('height', 1); $('#iframecontent').hide(); return false;\">Close window</a></p></div>";
        html += '<iframe width="100%" height="497" frameborder="0" src="/iframepage.aspx?folder=delivery-postage"></iframe>';
        
        $('#iframecontent').html(html);
        $('#iframecontent').show();

        $('#focuser').css('height', $('body').height() + 10);
        $('#focuser').addClass('darkenBackground');
        
        return false;
    });

    $('#returnspopuplink').bind('click', function() {
        $('#iframecontent').css('height', 530);
        $('#iframecontent').center();
        var html = "<div id=\"iframeheader\"><p><a href=\"#\" onclick=\"$('#focuser').removeClass(); $('#focuser').css('height', 1); $('#iframecontent').hide(); return false;\">Close window</a></p></div>";
        html += '<iframe width="100%" height="497" frameborder="0" src="/iframepage.aspx?folder=returns-exchanges"></iframe>';
        
        $('#iframecontent').html(html);
        $('#iframecontent').show();

        $('#focuser').css('height', $('body').height() + 10);
        $('#focuser').addClass('darkenBackground');
        
        return false;
    });
    
    $('#product-tabs li a').bind('click', function() {
        $('div.product-panel').css('display', 'none');
        $('#tab-main').css('background-color', '#55483B');
        $('#tab-detailedinfo').css('background-color', '#726151');
        $('#tab-sustainabilityinfo').css('background-color', '#BFA17B');
        $('#tab-reviews').css('background-color', '#DFC997');
        $('#product-tabs a').css('color', '#FFF');
        
        switch ($(this).attr('href'))
        {
            case "#tab0":
                SetCurrentTab('main');
                break;
            case "#tab1":
                SetCurrentTab('detailedinfo');
                break;
            case "#tab2":
                SetCurrentTab('sustainabilityinfo');
                break;
            case "#tab3":
                SetCurrentTab('reviews');
                break;
        }
    });

    $('.stocktable a[href^=outofstock], .stocktable-double a[href^=outofstock]').bind('click', function() {

    $('#stockcheck #pad').html('<div id="stockcheckprogress">&nbsp;</div>');
    
        $.get($(this).attr('href').replace(/outofstock/gi, 'ajaxoutofstock'), function(data) {
            $('#stockcheck').css('width', 720);
            $('#stockcheck #pad').html(data);

            $('#focuser').css('height', $('body').height() + 10);

            $('#stockcheck').center();
            $('#stockcheck').show();
            $('#focuser').addClass('darkenBackground');
        });

        return false;

    });

    $('#reviewform').hide();
    $('#reviewlink').bind('click', function() { $('#reviewform').show(); $(this).hide(); });

    var documentUrl = String(window.location.href).toLowerCase();
    var tabId = (documentUrl.indexOf("#tab") == -1) ? 0 : documentUrl.substr(documentUrl.indexOf("#tab") + 4);

    $('div.product-panel').css('display', 'none');
    $('#tab-main').css('background-color', '#55483B');
    $('#tab-detailedinfo').css('background-color', '#726151');
    $('#tab-sustainabilityinfo').css('background-color', '#BFA17B');
    $('#tab-reviews').css('background-color', '#DFC997');
    $('#product-tabs a').css('color', '#FFF');

    switch (Number(tabId))
    {
        case 1:
            SetCurrentTab("detailedinfo");
            break;
        case 2: 
            SetCurrentTab("sustainabilityinfo");
            break;
        case 3:
            SetCurrentTab("reviews");
            break;
        default:
            SetCurrentTab("main");
            break;
    }

});

function tab(tabName) {
        
    $('div.product-panel').css('display', 'none');
    $('#tab-main').css('background-color', '#55483B');
    $('#tab-detailedinfo').css('background-color', '#726151');
    $('#tab-sustainabilityinfo').css('background-color', '#BFA17B');
    $('#tab-reviews').css('background-color', '#DFC997');
    $('#product-tabs a').css('color', '#FFF');
    
    SetCurrentTab(tabName);
    
    document.location.hash = 'tab-' + tabName;
}

function SetCurrentTab(tabName)
{
    $('#panel-' + tabName).css('display', 'block');
    $('#tab-' + tabName + ' a').css('color', '#726151');
    $('#tab-main').css('background-image', 'url("/img/site/tab-main-inactive.gif")');
    $('#tab-detailedinfo').css('background-image', 'url("/img/site/tab-detailedinfo-inactive.gif")');
    $('#tab-sustainabilityinfo').css('background-image', 'url("/img/site/tab-sustainabilityinfo-inactive.gif")');
    $('#tab-reviews').css('background-image', 'url("/img/site/tab-reviews-inactive.gif")');
    switch(tabName)
    {
        case 'main':
            $('#tab-main').css('background-image', 'url("/img/site/tab-main-active.gif")');
            break;
        case 'detailedinfo':
            $('#tab-detailedinfo').css('background-image', 'url("/img/site/tab-detailedinfo-active.gif")');
            break;
        case 'sustainabilityinfo':
            $('#tab-sustainabilityinfo').css('background-image', 'url("/img/site/tab-sustainabilityinfo-active.gif")');
            break;
        case 'reviews':
            $('#tab-reviews').css('background-image', 'url("/img/site/tab-reviews-active.gif")');
            break;
        default:
            break;
    }
    // $('#product-tabs li').css('border-bottom', 'solid 1px #726151');
    // $('#tab-' + tabName).css('border-bottom', 'none');
}

function CloseWishList()
{
    $('#focuser').removeClass(); $('#focuser').css('height', 1); $('#stockcheck').hide();
}



function ChangeColour(colourCode) {
    //$('#img0, .productthumbl img, .productthumb img, .productthumbright img').each(function() {
    //    $(this).attr('src', $(this).attr('src').replace(/\d+\.jpg/gi, '1.jpg'));
    //});

    if ($('#' + colourCode + 'ImageData').val() != '') {
        var rawImageData = $('#' + colourCode + 'ImageData').val().split('|');

        var index = parseInt($('#ImageIndex').val(), 10);

        var id = 1;
        var alt= "";

        // Imagedata indexes (img[n]):
        // 0: Display order
        // 1: Image ID
        // 2: Caption/label
    
        for (var x = 0; x < rawImageData.length; x++) {

            var img = rawImageData[x].split('~');

            if (id == 1 && x==0)
            {
                id = img[1];
            }

            if(x > 0)
            {
                // Preload the other large images for this colour
                var preload = new Image();
                iurl = baseImagePreloadUrl + img[1] + '.jpg';
                preload.src = iurl;
            }

            var currentImg = $('#img' + img[0]);

            if (img[0] == index) 
            {
                // This is the current image that was being viewed, but in a different colour
                id = img[1];
                alt = img[2];
            }

            // Handle linked products - change the largish image above the matrix to the correct colour (left hand image)
            if ($('#linkimg1').length != 0 && img[0] == 2) {
                $('#linkimg1').attr('src', $('#linkimg1').attr('src').replace(/\d+\.jpg/gi, img[1] + '.jpg'));
                $('#linkimg1').attr('alt', img[2]);
            }
			
			if (currentImg.length > 0)
			{
				currentImg.attr('src', currentImg.attr('src').replace(/\d+\.jpg/gi, img[1] + '.jpg'));
				currentImg.attr('alt', img[2]);
			}

            if (img[1] == "1")
            {
                currentImg.hide();
            } else {
                currentImg.show();
            }
        }
		
        while (x < 5)
        {
            $('#img' + String(x+1)).hide();
            x++;
        }

        // Change the main large image on the page
        $('#img0').attr('src', $('#img0').attr('src').replace(/\d+\.jpg/gi, id +'.jpg'));
        $('#img0').parent().attr('href', $('#img0').attr('src').replace(/\/plge\//gi, '/pxlge/'));
        $('#img0').attr('alt', alt);
        
        // Handle the right hand image on the double product page
        if ($('#linkimg2').length != 0) {
            var rawLinkImageData = $('#Link' + colourCode + 'ImageData').val().split('|');

            for (var x = 0; x < rawLinkImageData.length; x++) {
                var img = rawLinkImageData[x].split('-');
                if (img[0] == 2) {
                    $('#linkimg2').attr('src', $('#linkimg2').attr('src').replace(/\d+\.jpg/gi, img[1] + '.jpg'));
                }
            }
        }
    }
    else {
        $('#img0').attr('src', '/img/lib/plge/1.jpg');
        $('#img0').parent().attr('href', '/img/lib/pxlge/1.jpg');
    }

    $('tr[class^=matrix] td').removeClass('colourhighlight');
    $('tr[class^=matrix] th').removeClass('colourhighlight');
    $('.matrix' + colourCode + ' td').addClass('colourhighlight');
    $('.matrix' + colourCode + ' th').addClass('colourhighlight');
}

function addToWishList(productCode)
{

    $.get('ajaxaddtowishlist/' + productCode + '/', function(data)
    {
        $('#stockcheck').css('width', 450);
        $('#stockcheck #pad').html(data);

        $('#focuser').css('height', $('body').height() + 10);

        $('#stockcheck').center();
        $('#stockcheck').show();
        $('#focuser').addClass('darkenBackground');
    });

    return false;
}

function showRecommendationForm() {

    $('#focuser').css('height', $('body').height() + 10);

    $('#recommendationform').center();
    $('#recommendationform').show();
    $('#focuser').addClass('darkenBackground');
    $('#recommendationform').show();

    return false;
}

function showReviewForm() {

    $('#focuser').css('height', $('body').height() + 10);

    $('#reviewform').center();
    $('#reviewform').show();
    $('#focuser').addClass('darkenBackground');
    $('#reviewform').show();

    return false;
}

function showSizeChart() {

    $('#focuser').css('height', $('body').height() + 10);

    $('#sizechartwindow').center();
    $('#sizechartwindow').show();
    $('#focuser').addClass('darkenBackground');
    $('#sizechartwindow').show();

    return false;
}

function validateRecommendationForm() {

	var emailRegex = /[a-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|edu)\b/gi;
	
	if (!$('#SenderEmail').val().match(emailRegex) || $('#SenderName').val() == '' || !$('#RecommendationEmail').val().match(emailRegex))
	{
		alert("Please enter your name and email address and the email address of the person you are sending the recommendation to.");
		return(false);
	} else {
		return(true);
	}
}

// Check the user has filled in both fields in the 'Product Review' form
function validateReviewForm()
{
    $('#reviewform .required').remove();

	if ($('#FullName').val() == "")
	{
        $('#reviewform textarea').parent().after('<p class="required">You must fill in your name.</p>');
        return false;
	}

    var email = $('#Email').val();
    var emailRegex = /[a-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b/gi;

    if(email == '')
    {
        $('#reviewform textarea').parent().after('<p class="required">You must fill in your email address.</p>');
        return false;
    }
    else if(!email.match(emailRegex))
    {
        $('#reviewform textarea').parent().after('<p class="required">The email address you entered is not a valid address.</p>');
	    return false;
    }
    else
    {
        return true;
    }
}

