/*
	Collections Javascript
 */
function PopulateSizeDetails(subCollectionObject, currObject, initial)
{
    $.ajax({
        url: urlbase + "/GetSizesHtml",
        data: $.toJSON({ productcollection: subCollectionObject.val(), productmodel: currObject.val() }),
        dataType: "text",
        success: function(data) {

            var xml = $.xmlDOM(data);
            // Returned data available in object "xml"

            if (xml) {
                var sizeObject = currObject.parents().filter('div .quickbuy').find('select').filter('.Size');
                var headerObject = currObject.parents().filter('div .quickbuy').find('.header');
                var productObject = currObject.parents().filter('div .quickbuy').find('select').filter('.Options');

                sizeObject.html(xml.find('root').text());

                if (initial) {
                    try {
                        headerObject.html(currObject[0].children[0].text);
                    }
                    catch (Error) {
                        headerObject.html(currObject[0].options[0].text);
                    }
                }
                else {
                    headerObject.html(currObject.context[currObject.context.selectedIndex].text);
                }

                var sizeLabelText = xml.find('root > SizeHeading').text();

                if (sizeLabelText != "") {
                    var sizeLabel = currObject.parents().filter('div .quickbuy').find('.SizeLabel');

                    sizeLabel.html(sizeLabelText);
                }

                var dimensionsLabelText = xml.find('root > DimensionsHeading').text();

                if (dimensionsLabelText != "") {
                    var dimensionsLabel = currObject.parents().filter('div .quickbuy').find('.DimensionsLabel');

                    dimensionsLabel.html(dimensionsLabelText);
                }
                
                PopulateDimensionDetails(productObject, sizeObject, true);
            }
        }
    });  
}

function PopulateSizeDetailsFromDimensions(productModel, productDimensions, initial)
{
    $.ajax({
        url: urlbase + "/GetSizesFromDimensionsHtml",
        data: $.toJSON({ productmodelid: productModel.val(), productdimension: productDimensions[0][productDimensions[0].selectedIndex].text }),
        dataType: "text",
        success: function(data) {
             var xml = $.xmlDOM(data);
           if (xml) {
                    
                var sizeObject = productDimensions.parents().filter('div .quickbuy').find('select').filter('.Size');
                             
                sizeObject.unbind("onchange");
               
                sizeObject.html(xml.find('root').text()); 
                
                
                PopulateDimensionDetailsAfterPostBack(productModel, sizeObject, true)
                         
            }
        }
    });  
}

function PopulateDimensionDetailsAfterPostBack(productModel, productSize, initial) {

    $.ajax({
        url: urlbase + "/GetDimensionsHtml",
        data: $.toJSON({ productmodelid: productModel.val(), productsize: productSize[0][productSize[0].selectedIndex].value }),
        dataType: "html",
        success: function(html) {

            if (html) {
                var heightObject = productModel.parents().filter('div .quickbuy').find('select').filter('.select_height');
                var priceObject = productModel.parents().filter('div .quickbuy').find('.price_value');
                var quantityObject = productModel.parents().filter('div .quickbuy').find('.Qty');
                heightObject.html(html);
                var quantity = parseInt(quantityObject[1].value);
                
                try
                {
                var selectedPrice = heightObject[0][heightObject.context.selectedIndex].attributes["price"].value;
                var specialprice = heightObject[0][heightObject.context.selectedIndex].attributes["specialprice"].value;
                selectedPrice = selectedPrice.replace("£",""); 
                specialprice =  specialprice.replace("£","");   
                var specialPriceObject = productModel.parents().filter('div .quickbuy').find('.specialPrice_value');
                specialPriceObject.html(heightObject[0][heightObject.context.selectedIndex].attributes["specialprice"].value);
                var parsedPrice = parseFloat(selectedPrice);
                var specialParsedPrice = parseFloat(specialprice);
                var priceForQuantity;
                var finalPrice;
                var totalPrice;
                
                if (parsedPrice == specialParsedPrice)
                  {
                    priceForQuantity = parsedPrice;
                    totalPrice = quantity * priceForQuantity;
                    finalPrice = totalPrice.toFixed(2);
                    priceObject.html("&pound;" + finalPrice);
                    priceObject.css("color","green");
                    priceObject.css("text-decoration","none");
                    specialPriceObject.hide();
                  }
                 else
                  {
                    priceForQuantity = specialParsedPrice; 
                    totalPrice = quantity * priceForQuantity;
                    finalPrice = totalPrice.toFixed(2);                   
                    specialPriceObject.html("&pound;" + finalPrice);
                    var totalInitPrice;
                    totalInitPrice = quantity * parsedPrice;
                    totalInitPrice = totalInitPrice.toFixed(2); 
                    priceObject.html("&pound;" + totalInitPrice);
                    priceObject.css("color","red");
                    priceObject.css("text-decoration","line-through");
                    specialPriceObject.show();
                  }
                  }
                  catch (Error){}
                GenerateAddToBasketButton(heightObject);
            }
        }
    });
}

function PopulateDimensionDetails(productModel, productSize, initial) {

    $.ajax({
        url: urlbase + "/GetDimensionsHtml",
        data: $.toJSON({ productmodelid: productModel.val(), productsize: productSize[0][productSize[0].selectedIndex].value }),
        dataType: "html",
        success: function(html) {

            if (html) {
                var heightObject = productModel.parents().filter('div .quickbuy').find('select').filter('.select_height');
                var priceObject = productModel.parents().filter('div .quickbuy').find('.price_value');
                var quantityObject = productModel.parents().filter('div .quickbuy').find('.Qty');
                heightObject.html(html);
                var quantity = parseInt(quantityObject[1].value);
                var selectedPrice;
                var specialprice;
                
                try
                {
                if (initial)
                {
                    selectedPrice = heightObject[0][0].attributes["price"].value;
                    specialprice = heightObject[0][0].attributes["specialprice"].value;
                }
                else
                {
                    selectedPrice = heightObject[0][heightObject.context.selectedIndex].attributes["price"].value;
                    specialprice = heightObject[0][heightObject.context.selectedIndex].attributes["specialprice"].value;
                }
                
                selectedPrice = selectedPrice.replace("£",""); 
                specialprice =  specialprice.replace("£","");   
                
                var parsedPrice = parseFloat(selectedPrice);
                var specialParsedPrice = parseFloat(specialprice);
                var specialPriceObject = productModel.parents().filter('div .quickbuy').find('.specialPrice_value');
                var priceForQuantity;
                var finalPrice;
                var totalPrice;
               
                if (parsedPrice == specialParsedPrice)
                  {
                    priceForQuantity = parsedPrice;
                    totalPrice = quantity * priceForQuantity;
                    finalPrice = totalPrice.toFixed(2);
                    priceObject.html("&pound;" + finalPrice);
                    priceObject.css("color","green");
                    priceObject.css("text-decoration", "none");
                    priceObject.css("padding-right", "5px");
                    specialPriceObject.hide();
                    
                  }
                 else
                  {
                    priceForQuantity = specialParsedPrice; 
                    totalPrice = quantity * priceForQuantity;
                    finalPrice = totalPrice.toFixed(2);                   
                    specialPriceObject.html("&pound;" + finalPrice);
                    var totalInitPrice;
                    totalInitPrice = quantity * parsedPrice;
                    totalInitPrice = totalInitPrice.toFixed(2); 
                    priceObject.html("&pound;" + totalInitPrice);
                    priceObject.css("color","red");
                    priceObject.css("text-decoration","line-through");
                    specialPriceObject.show();
                  }             
                 
                }
                catch (Error) {}
                
                GenerateAddToBasketButton(heightObject);
            }
        }
    });
}

function PopulateDescriptionDetails(currObject)
{
    $.ajax({
	    url: urlbase + "/GetDescriptionHtml",
	    data: $.toJSON({ productcollection: currObject.val() }),
	    dataType: "html",	    
	    success: function(html) {
	        
		    if (html) {
		       
		          try{
		          var descriptionObject = currObject.parents().filter('div .quickbuy').find('.product_description');
		          	 
		            descriptionObject.html(html);     
		            }
		            
		            catch(Error)
		            {
		            }
		   }
	    }
    });  
}

function PopulateImageDetails(currObject)
{
    $.ajax({
	    url: urlbase + "/GetImageHtml",
	    data: $.toJSON({ productcollection: currObject.val() }),
	    dataType: "html",	    
	    success: function(html) {
	        
		    if (html) {
		          
		          try{
		          
		          var imageObject = currObject.parents().filter('div .quickbuy').prevAll().find('.imageType');
		          	     
		            imageObject.html(html); 
		            }
		            catch (Error)
		            {
		            }
		          
		             
		   }
	    }
    });  
}

function PopulateDropDownsAndChangeCollectionDetails(currObject)
{

    $.ajax({
        url: urlbase + "/GetCollectionDetails",
        data: $.toJSON({ subcollection: currObject.val() }),
        success: function(collections) {

            if (collections) {

            
                var products = collections["products"].replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"');

                var productObject = currObject.parents().filter('div .quickbuy').find('select').filter('.Options');
                var headerObject = currObject.parents().filter('div .quickbuy').find('.header');
                var subCollectionObject = currObject.parents().find('.subCollectionType');
               
                productObject.html(products);
                PopulateSizeDetails(subCollectionObject, productObject, true);
                
                                try {
                    PopulateDescriptionDetails(productObject);
                }
                catch (Error)
		          { }
                try {
                    
                    PopulateImageDetails(productObject);
                    
                }
                catch (Error)
		          { }
		         
            }
        }
    }); 
}

function GenerateAddToBasketButton(currObject)
{
         var buynowobject = currObject.parents().filter('div .quickbuy').find('.add');
         var quantityobject = currObject.parents().filter('div .quickbuy').find('.qty_value');
         var salesorderid = $("#salesorderid").text();
         var affiliateid = $("#affiliateid").text();
             salesorderid = salesorderid + 0;
             affiliateid = affiliateid + 0;
       
         quantityobject[0].id = "productname" + currObject.val();
         
          
         $.ajax({
          url: urlbase + "/GetFreeStockHtml",
          data: $.toJSON({ productid: currObject.val()}),
          success: function(html) {
            var stock = html + 0;
            if (stock == 0)
            {
            
		    var outOfStockhtml = "The item selected is currently out of stock";    
		    buynowobject.html(outOfStockhtml);
            }
            else{
            var buynowhtml = "<a href='#basket_overlay' onclick='javascript:GoToAddBasket(" + salesorderid + "," + currObject.val() + "," + quantityobject[0].id + ");' class='nyroModal'>Add To Basket</a>";
             buynowobject.html(buynowhtml);
            }

            
         
         
          }
      });
             	            
		            
}

function GoToAddBasket(salesorderid, currValue, quantId)
{
        
      var quantity;
      try{
      
         
      quantity = quantId.all[0].value;
      }
      catch (Error)
      {
      try {
      quantity = quantId.childNodes[0].value;
      }
      catch (Error)
      {
       quantity = quantId[0].childNodes[0].value;
      }
      }
      $.ajax({
          url: urlbase + "/AddProductsToBasket",
          data: $.toJSON({ productid: currValue, quantity: quantity, salesorder: salesorderid }),
          success: function(html) {

              $("#basket_overlay").show();

              showPopUp('basket_overlay');
              var blurDiv = document.createElement("div");
              blurDiv.id = "blurDiv";
              blurDiv.style.cssText = "position:absolute; top:0; right:0; width:" + screen.width + "px; height:" + window.document.body.scrollHeight + "px; background-color: #000000; opacity:0.5; filter:alpha(opacity=50)";

              document.getElementsByTagName("body")[0].appendChild(blurDiv);

              $("#blurDiv").bgiframe();

              //$(".basketlite").before(html).remove();
          }
      });
      
}

function ShowBasketOverlay() {
    $("#basket_overlay").show();
	 $("#basket_overlay").focus();
}


var g_PopupIFrame;

function IsIE()
{

return ( navigator.appName=="Microsoft Internet Explorer" );

}

function HideIframe()
{


if (IsIE())
{

//document.body.removeChild(g_PopupIFrame);
//g_PopupIFrame=null;

}

}

function ShowPopupIframe(divID)
{

var divPopup=document.getElementById(divID);

//Increase default zIndex of div by 1, so that DIV appears before IFrame
divPopup.style.zIndex=divPopup.style.zIndex+1;

var iFrame = document.createElement("IFRAME");
iFrame.setAttribute("src", "");

//Match IFrame position with divPopup
iFrame.style.position="absolute";
iFrame.style.left =divPopup.offsetLeft + 'px';
iFrame.style.top =divPopup.offsetTop + 'px';
iFrame.style.width =divPopup.offsetWidth + 'px';
iFrame.style.height =divPopup.offsetHeight + 'px';

document.body.appendChild(iFrame);


}



function HideBasketOverlay() {
    $.nyroModalRemove();
    return false;
}

var urlbase;
$(document).ready(function() {
    $.ajaxSetup({
	    type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8"        
    });
    
    urlbase = $("#urlbase").val();
    
    var subCollectionObject = $('.subCollectionType');
    var productObject = $('.productType');
    var sizeObject = $('.sizeType');
    var heightObject = $('.select_height');
	var quantityObject = $('.Qty');

                    
    subCollectionObject.each(function () {
        var currentObject = $(this);
        
        PopulateDropDownsAndChangeCollectionDetails(currentObject);
    });
    
    subCollectionObject.change(function(){
        var currentObject = $(this);
        PopulateDropDownsAndChangeCollectionDetails(currentObject);
    }); 
    
    productObject.change(function(){
        var currentObject = $(this);

        var subCollectionObject = currentObject.parents().find('.subCollectionType');
       
        PopulateSizeDetails(subCollectionObject, currentObject, false);
        PopulateDescriptionDetails(currentObject);
        PopulateImageDetails(currentObject);
    });

    sizeObject.change(function () {
        var currentObject = $(this);
        var productObject = currentObject.parents().filter('div .quickbuy').find('select').filter('.Options');
       
        PopulateDimensionDetails(productObject, currentObject, false);
    });

    heightObject.change(function() {
        var currentObject = $(this);
        var priceObject = currentObject.parents().filter('div .quickbuy').find('.price_value');
        var specialPriceObject = currentObject.parents().filter('div .quickbuy').find('.specialPrice_value');
         var productObject = currentObject.parents().filter('div .quickbuy').find('select').filter('.Options');
         
        PopulateSizeDetailsFromDimensions(productObject, currentObject, false);
         
       
        priceObject.html(currentObject.context[currentObject.context.selectedIndex].attributes["price"].value);
        var specialPriceObject = currentObject.parents().filter('div .quickbuy').find('.specialPrice_value');
        specialPriceObject.html(currentObject.context[currentObject.context.selectedIndex].attributes["specialprice"].value);
        GenerateAddToBasketButton(currentObject);
         
    }); 
	
	quantityObject.change(function() {
        var currentObject = $(this);
        var heightObject = currentObject.parents().filter('div .quickbuy').find('.select_height');
        var priceObject = currentObject.parents().filter('div .quickbuy').find('.price_value');
        var quantity = parseInt(currentObject[0].value);
        
        var selectedPrice = heightObject[0][heightObject[0].selectedIndex].attributes["price"].value;
        var specialprice = heightObject[0][heightObject[0].selectedIndex].attributes["specialprice"].value;
        var specialPriceObject = currentObject.parents().filter('div .quickbuy').find('.specialPrice_value');
        specialPriceObject.html(heightObject[0][heightObject[0].selectedIndex].attributes["specialprice"].value); 
        selectedPrice = selectedPrice.replace("£",""); 
        specialprice =  specialprice.replace("£","");    
        var parsedPrice = parseFloat(selectedPrice);
        var specialParsedPrice = parseFloat(specialprice);
         var priceForQuantity;
                var finalPrice;
                var totalPrice;
                
                if (parsedPrice == specialParsedPrice)
                  {
                    priceForQuantity = parsedPrice;
                    totalPrice = quantity * priceForQuantity;
                    finalPrice = totalPrice.toFixed(2);
                    priceObject.html("&pound;" + finalPrice);
                    priceObject.css("color","green");
                    priceObject.css("text-decoration","none");
                    specialPriceObject.hide();
                  }
                 else
                  {
                    priceForQuantity = specialParsedPrice; 
                    totalPrice = quantity * priceForQuantity;
                    finalPrice = totalPrice.toFixed(2);                   
                    specialPriceObject.html("&pound;" + finalPrice);
                    var totalInitPrice;
                    totalInitPrice = quantity * parsedPrice;
                    totalInitPrice = totalInitPrice.toFixed(2); 
                    priceObject.html("&pound;" + totalInitPrice);
                    priceObject.css("color","red");
                    priceObject.css("text-decoration","line-through");
                    specialPriceObject.show();
                  }
        
        
    });  
});    

