﻿// JScript File

function GetXmlHttpObject() {
    var xmlHttp = null;

    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
        // Internet Explorer
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }

    return xmlHttp;
}

function submitQuestionForm(prodID) {
    var xmlHttp = GetXmlHttpObject();
	
    if (xmlHttp == null) {
        alert("Your browser does not support AJAX!");
        return;
    }
    
    var email = document.getElementById('qEmail').value;
    var name = document.getElementById('qName').value;
    var telephone = document.getElementById('qTelephone').value;
    var question = document.getElementById('qQuestion').value;
	
    var url = "/ajaxSubmitQuestionForm?prodID=" + prodID + "&email=" + email + "&name=" + name + "&telephone=" + telephone + "&question=" + question;

    xmlHttp.onreadystatechange= function() { submitQuestionFormFinished(xmlHttp); }

    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}

function submitQuestionFormFinished(xmlHttp) {
    if (xmlHttp.readyState == 4) {
        var rnObj = xmlHttp.responseText;
        if (rnObj != "SUCCESS")
        {
            document.getElementById('AskQuestionDivContent').innerHTML = "Sorry, there was an error with your request, please try again later";
        }
        else 
        {
            document.getElementById('AskQuestionDivContent').innerHTML = document.getElementById('questionConfirm').innerHTML;
        }
    }
}

function submitReviewForm(prodID) {
    var xmlHttp = GetXmlHttpObject();
	
    if (xmlHttp == null) {
        alert("Your browser does not support AJAX!");
        return;
    }
    
    var name = document.getElementById('review-name').value;
    var email = document.getElementById('review-email').value;
    var review = document.getElementById('review-reviewtext').value;
    var rating = document.getElementById('review-rating').value;
	
    var url = "/ajaxSubmitReviewForm?prodID=" + prodID + "&name=" + name + "&email=" + email + "&review=" + review + "&rating=" + rating;

    xmlHttp.onreadystatechange= function() { submitReviewFormFinished(xmlHttp); }

    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}

function submitReviewFormFinished(xmlHttp) {
    if (xmlHttp.readyState == 4) {
        var rnObj = xmlHttp.responseText;
        if (rnObj == "SUCCESS")
        {
            document.getElementById('AddReviewDivContent').innerHTML = document.getElementById('reviewConfirm').innerHTML;
        }
        else if (rnObj == "LOGIN")
        {
            document.getElementById('AddReviewDivContent').innerHTML = "You are not logged in. Please login to post a review";
        }
        else
        {
            document.getElementById('AddReviewDivContent').innerHTML = "Sorry, there was an error with your request, please try again later";
        }
    }
}

function changeProductSizes(prodID, type) {
    var xmlHttp = GetXmlHttpObject();
	
    if (xmlHttp == null) {
        alert("Your browser does not support AJAX!");
        return;
    }
    
    document.getElementById('product-specification-controller').innerHTML = "<div id='prodSpecLoading'>Fetching " + type + " sizes...</div>";
    window.location.hash = "product-specification-controller";
    	
    var url = "/ajaxProdSpecificationBox?prodID=" + prodID + "&type=" + type;

    xmlHttp.onreadystatechange= function() { changeProductSizesFinished(xmlHttp); }

    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}

var isDD = false;

function changeProductSizesFinished(xmlHttp) {
    if (xmlHttp.readyState == 4) {
        document.getElementById('product-specification-controller').innerHTML = xmlHttp.responseText;
        calculateSubOptions();
        setupElementsForJS();
    }
}

function setupElementsForJS()
{
    //first, i would like to just get to know you
    document.getElementById("product-navigation-container").style.display = "block";
    //now i'm gonna ask you a bunch of questions, and i wanna hav them answered immediately!
    for (var idx = 0, len = productOptions.length; idx < len; idx++)
    {
        document.getElementById("change-measurements-dt-" + idx).style.display = "block";
        document.getElementById("change-measurements-dd-" + idx).style.display = "block";
    }
}

function pickProductOption()
{
    //find the product-sizes select populated by the server
    var eles = document.getElementsByTagName("select");
    var ele = null;

	var optionID = 0;
	var selectedIndex = 0;

	for (var idx = 0, len = document.getElementsByName('pos').length; idx < len; idx++) {

		if (document.getElementsByName('pos')[idx].checked == true) {
			optionID = document.getElementsByName('pos')[idx].value;
			selectedIndex = idx;
			
			break;
		}
	}

/*    for (var idx = 0, len = eles.length; idx < len; idx++)
    {
        if (eles[idx].className == "product-size")
        {
            ele = eles[idx];
            //if there is only 1 option then hide the drop-down as it's unnecessary
            if (ele.options.length == 1) ele.style.display = "none";
        }
    }
*/
        
    //update the optionID in the optionID input field
    document.getElementById("optionID").value = optionID;
    
    //show or hide the add to basket button
    if (document.getElementById("add-to-basket-main") != null)
    {
        if (productOptions[selectedIndex].isAvailable == "True")
        {
            document.getElementById("add-to-basket-main").innerHTML = "<input type='image' src='/assets/images/layout/add-to-basket.gif' alt='Add To Basket' />"
        }
        else 
        {
            document.getElementById("add-to-basket-main").innerHTML = "<b>Currently out of stock</b>";
        }
    }
    
    calculateSubOptions(optionID, selectedIndex);
    updateTotalPrice(optionID, selectedIndex);
    updateDeliveryInfo(optionID, selectedIndex);
    updateOptionalExtras(optionID, selectedIndex);
    updateAdditionalInfo(optionID, selectedIndex);
}

function calculateSubOptions(optionID, selectedIndex)
{ //for the currently selected option
    
    //find the product-sizes select populated by the server
    var eles = document.getElementsByTagName("select");
    var ele = null;

	var optionID = 0;
	var selectedIndex = 0;

	for (var idx = 0, len = document.getElementsByName('pos').length; idx < len; idx++) {

		if (document.getElementsByName('pos')[idx].checked == true) {
			optionID = document.getElementsByName('pos')[idx].value;
			selectedIndex = idx;
			
			break;
		}
	}
        
    var curOpExtras = document.getElementById("optionalExtras_" + selectedIndex);
    var inputs = curOpExtras.getElementsByTagName("input");
    var selects = curOpExtras.getElementsByTagName("select");
    var suboptionsl = [];
    var suboptionsPrices = [];
	
    for (var idx = 0, len = inputs.length; idx < len; idx++) {
        var eleInput = inputs[idx];
	
        if (eleInput.id.indexOf("subOp_") == 0) {
	        if (eleInput.checked == true) {
		        suboptionsl.push(eleInput.id.replace("subOp_", ""));
		        suboptionsPrices.push(eleInput.value);
	        }
        }
    }
        
    for (var idx = 0, len = selects.length; idx < len; idx++) {
        var eleSelect = selects[idx];
	
        if (eleSelect.id.indexOf("subOpSel_") == 0) {
            //see if the customer has selected to receive one of these by the checkbox status
            for (var jdx = 0, lenj = inputs.length; jdx < lenj; jdx++) {
                var eleInput = inputs[jdx];
                if (eleInput.id == ("subOpGroup_" + eleSelect.id.split('_')[1]))
                {
                    if (eleInput.checked == true)
                    {
                        var selectValue = eleSelect.options[eleSelect.selectedIndex].value;
                        suboptionsl.push(selectValue.split('_')[0]);
                        suboptionsPrices.push(selectValue.split('_')[1]);
                    }
                }
            }
        }
    }
	
    document.getElementById('suboptions').value = suboptionsl.join(",");
    document.getElementById('suboptionsprices').value = suboptionsPrices.join(",");
    
    //update the technical specs inputs
    var techSpecsEle = document.getElementById('suboptions' + selectedIndex);
    if (techSpecsEle != null) techSpecsEle.value = suboptionsl.join(",");
    
    //update the optional extras inputs
    var extrasEle = document.getElementById('extras_suboptions' + selectedIndex);
    if (extrasEle != null) extrasEle.value = suboptionsl.join(",");
        
    updateTotalPrice(optionID, selectedIndex);
}

function updateTotalPrice(optionID, selectedIndex)
{            
    var option = productOptions[selectedIndex];
    var totalPrice = parseFloat(option.price);
    var pricesEle = document.getElementById("suboptionsprices").value.split(',');
    var subOpTotalPrice = 0;
    var withSubOps = false;
    if ((pricesEle.length > 0)&&(pricesEle[0] != ""))
    {
        withSubOps = true;
        for (var idx = 0, len = pricesEle.length; idx < len; idx++)
        {
            totalPrice += parseFloat(pricesEle[idx]);
            subOpTotalPrice += parseFloat(pricesEle[idx]);
        }
    }
    
    //update the main product price
    var priceBits = totalPrice.toString().split('.');
    //if there is a 'pence' bit
    if (priceBits.length > 1)
    {
        //make sure there is at least two characters here
        if (priceBits[1].length == 1)
        {
            priceBits[1] += "0";
        }
        totalPrice = priceBits[0] + "." + priceBits[1].substr(0,2);
    }
    else 
    { //no pence bit so stick some on
		totalPrice += ".00";
    }
    
    if (document.getElementById("product-price") != null)
    {
        if (withSubOps)
        {
            document.getElementById("product-price").innerHTML = "Total Price: &pound;" + totalPrice + " (with extras)";
        }
        else 
        {
            document.getElementById("product-price").innerHTML = "Total Price: &pound;" + totalPrice;
        }
    }
        
    //update the prices of the relevant option
    var optionDefaultPrice = document.getElementById("optionTotalDefault" + selectedIndex);
    if (optionDefaultPrice != null)
    {
        optionDefaultPrice = parseFloat(optionDefaultPrice.value);
        var optionTotal = optionDefaultPrice + subOpTotalPrice;
        
        if ((optionTotal + "").indexOf(".") != -1) {
			var optionTotalBits = (optionTotal + "").split(".");
			optionTotal = optionTotalBits[0] + "." + optionTotalBits[1].substr(0, 2);
        }
        
        var optionString = "&pound;" + optionTotal;
        if (withSubOps)
        {
            optionString += " (with extras)";
        }
        if (document.getElementById("optionTotal" + selectedIndex) != null)
        {
            document.getElementById("optionTotal" + selectedIndex).innerHTML = optionString;
        }
    }
    //update the prices in the optional extras bit
    var extrasOptionDefaultPrice = document.getElementById("extras_optionTotalDefault" + selectedIndex);
    if (extrasOptionDefaultPrice != null)
    {
        extrasOptionDefaultPrice = parseFloat(extrasOptionDefaultPrice.value);
        var optionTotal = extrasOptionDefaultPrice + subOpTotalPrice;
        
        if ((optionTotal + "").indexOf(".") != -1) {
	        var optionTotalBits = (optionTotal + "").split(".");
			optionTotal = optionTotalBits[0] + "." + optionTotalBits[1].substr(0, 2);
		}
		
        var optionString = "&pound;" + optionTotal;
                
        if (withSubOps)
        {
            optionString += " (with extras)";
        }
        if (document.getElementById("extras_optionTotal" + selectedIndex) != null)
        {
            document.getElementById("extras_optionTotal" + selectedIndex).innerHTML = optionString;
        }
    }
}

function updateDeliveryInfo(optionID, selectedIndex)
{
    if (document.getElementById("productDelivery") != null)
    {
        document.getElementById("productDelivery").innerHTML = "<div id='product-delivery-details'><p>Delivery usually <b><span id='del-time'>" + productOptions[selectedIndex].deliveryDays + "</span> working days</b><br><a href='/termsandconditions'>Click here for full terms &amp; conditions</a></p></div>"
    }
}

function updateOptionalExtras(optionID, selectedIndex)
{
    //hide all of the optional extras tables
    for (var idx = 0, len = productOptions.length; idx < len; idx++)
    {
        var curEle = document.getElementById("optionalExtras_" + idx);
        if (curEle != null) curEle.style.display = "none";
    }
    document.getElementById("optionalExtras_" + selectedIndex).style.display = "block";
}

function updateAdditionalInfo(optionID, selectedIndex)
{            
    //hide all the info
    for (var idx = 0, len = productOptions.length; idx < len; idx++)
    {
        var curEle = document.getElementById("addInfo_" + idx);
        if (curEle != null) curEle.style.display = "none";
    }
    //show the one we want
    document.getElementById("addInfo_" + selectedIndex).style.display = "block";          
}

function showHideFAQAnswer(faqid)
{
    if (document.getElementById(faqid).style.display != "block")
    {
        document.getElementById(faqid).style.display = "block";
    }
    else 
    {
        document.getElementById(faqid).style.display = "none";
    }
}

function showHideSections(idToShow, listEleId)
{
    //hide all elements
    if (!isDD)
    {
        var blockEle = document.getElementById("product-overview-container");
        if (blockEle != null) blockEle.style.display = "none";
        var listEle = document.getElementById("liOverview");
        if (listEle != null) listEle.className = "";
    }
    
    blockEle = document.getElementById("product-specification-container");
    if (blockEle != null) blockEle.style.display = "none";
    var listEle = document.getElementById("liSpec");
    if (listEle != null) listEle.className = "";
    
    blockEle = document.getElementById("optional-extras-container");
    if (blockEle != null) blockEle.style.display = "none";
    var listEle = document.getElementById("liExtras");
    if (listEle != null) listEle.className = "";
    
    blockEle = document.getElementById("compare-products-container");
    if (blockEle != null) blockEle.style.display = "none";
    var listEle = document.getElementById("liCompare");
    if (listEle != null) listEle.className = "";
    
    blockEle = document.getElementById("additional-information-container");
    if (blockEle != null) blockEle.style.display = "none";
    var listEle = document.getElementById("liAdditionalInfo");
    if (listEle != null) listEle.className = "";
    
    //show desired element
    blockEle = document.getElementById(idToShow);
    if (blockEle != null) blockEle.style.display = "block";
    listEle = document.getElementById(listEleId);
    if (listEle != null) listEle.className = "current";
}

function goToWarranty()
{
    var warrantyEle = document.getElementById("product-warranty");
    if (warrantyEle != null)
    {
        showHideSections("additional-information-container", "liAdditionalInfo");
        window.location.hash = "product-warranty";
    }
}

//review stars ------------------------------------------------
function newImage(arg) {
    if (document.images) {
        var rslt = new Image();
        rslt.src = arg;
        return rslt;
    }
}
var preloadFlag = false;
function preloadImages() {
    if (document.images) {
        var starOn = newImage('/assets/images/layout/star1.gif');
        preloadFlag = true;
    }
}
function starMouseOver( rate ) {
    document.getElementById("review-rating").value = rate;
    var i;
    for ( i=0; i<rate; i++ ) {
        document.getElementById('star' + ((i) + 1 )).src = '/assets/images/layout/star1.gif';
    }
    for ( i=5; rate<i; i-- ) {
        document.getElementById('star' + i).src = '/assets/images/layout/star2.gif';
    }
}
function starMouseOut() {
    var rate = document.getElementById("review-rating").value;
    var i;
    for ( i=5; rate<i; i-- ) {
        document.getElementById('star' + i).src = '/assets/images/layout/star2.gif';
    }
}
function starSelectRate( rate ) {
    document.getElementById("review-rating").value = rate;
    if (document.getElementById('ratingText') != null)
    {
        if( rate == 1 ) {
            document.getElementById('ratingText').innerHTML = 'You have rated it 1 star';
        }
        else {
            document.getElementById('ratingText').innerHTML = 'You have rated it ' + rate + ' stars';
        }
    }
}
function unselect() {
    for ( i=1; i<=5; i++ ) {
        document['star' + i].src = '/assets/images/layout/star2.gif';
    }
    document.getElementById("review-rating").value = "0";
    if (document.getElementById('ratingText') != null)
    {
        document.getElementById("ratingText").innerHTML = 'You have rated it zero stars';
    }
}                   	
preloadImages();
//-----------------------------------------------------------------------------