/*
 * Global Javascript 
 * 
 */
var zconfig = {
    zoomWidth: 428, // zooming div default width (default is 200)
    zoomHeight: 423, // zooming div default height (default is 200)
    xOffset: 15, // zooming div offset (default is 10)
    yOffset: 0,
    position: "right", // zooming dif position (default is "right")
    preloadImages: false, // preload zoom image (default is 1 "true")
    title: true,
    showEffect: 'fadein',
    hideEffect: 'fadeout',
    fadeinSpeed: "medium",
    fadeoutSpeed: "slow",
    zoomType: "reverse",
    imageOpacity: 0.65
};

var sit = new SITEINTEL.SiteTracker(true);
var oldQtys = new Array();

$(document).ready(function(){

	/* Global Actions */

	$("#logout").click(function(){
		$("#logoutForm").submit();
	});

	$("#siteQ").submit(function(e){
		e.preventDefault();
		window.location = '/search/q/' + escape($("#sq").val()).replace('/','%2F');
	});
	

	//Overlay setup
	$("body")
	  .append($('<div id="overlay" class="apple_overlay" />')
	  .append($('<div class="contentWrap"/>')
	  .append($('<iframe id="icontainer" frameborder="no" scrolling="auto"/>'))
	));
	
	function overlayClick(){
  	  $(".bvOverlay").overlay({
		  expose: '#808080',
		  effect: 'apple',
		  closeOnClick: false,

		  onBeforeLoad: function() {
		    $('body').css({ 'overflow' : 'hidden' });
		    var $wrap = this.getContent().find(".contentWrap");
		    var $icontainer = $wrap.find("#icontainer");
		    $icontainer.attr("src",this.getTrigger().attr("href"));
		  },

		  onClose: function() {
		    $('body').css({ 'overflow' : 'visible' });
		  }

		});
	}

	overlayClick();

	// Homepage
	$(".homepage").each(function(){
		$("#vplayer").flowplayer({ src: "/static/flowplayer.commercial-3.1.5.swf", wmode: 'opaque'}, {
			key : fpk,
			plugins : {
				controls : {
					backgroundColor : '#000',
					backgroundGradient : 'none',
					all : false,
					scrubber : true,
					play : true,
					volume: true,
					mute: true,
					buttonColor : '#333333',
					buttonOverColor : '#ca000a',
					sliderColor : '#333333',
					volumeSliderColor: '#ca000a',
					progressColor : '#ca000a',
					bufferColor : '#666666',
					tooltipColor : '#ca000a',
					tooltipTextColor : '#ffffff'
				}
			}
		});
		$("#vplayer").each(function(){$f("vplayer").playlist("#vselections")});
	});


	    if ($("#myzoom").attr("href") != '') {
		$("#myzoom").jqzoom(zconfig);
		// Horrible Hack - IE8
		if ($.browser.msie) {
	        	$("#myzoom").attr({
	        	    href: $("#myzoom img").attr('src').replace(/\xl.jpg$/, "xxl.jpg"),
	        	    title: $("#img-name h1").html()
	        	}).jqzoom(zconfig);
	    	}

	    }

	    $("#btn-photo").click(function(e){
	        e.preventDefault();
		$(this).siblings().removeClass('selected').end().addClass('selected');
	        stopVideo();
	    });
	    
	    $("#btn-video").click(function(e){
	        e.preventDefault();
		$(this).siblings().removeClass('selected').end().addClass('selected');
	        playVideo();
	    });

	$("#player").flowplayer({ src: "/static/flowplayer.commercial-3.1.5.swf", wmode: 'transparent'}, {
		key : fpk,
		plugins : {
			controls : {
				backgroundColor : '#000',
				backgroundGradient : 'none',
				all : false,
				scrubber : true,
				play : true,
				volume: true,
				mute: true,
				loop : true,
				buttonColor : '#333333',
				buttonOverColor : '#ca000a',
				sliderColor : '#333333',
				volumeSliderColor: '#ca000a',
				progressColor : '#ca000a',
				bufferColor : '#666666',
				tooltipColor : '#ca000a',
				tooltipTextColor : '#ffffff'
			}
		},
		clip : {
			onBeforeFinish : function() {
				this.play(0);
				return false;
			},
			onBegin : function() {
				this.getPlugin("play").css( {
					opacity : 0
				});
			},
			onFinish : function() {
				this.getPlugin("play").hide();
			}
		}
	});

	if (typeof product != "undefined") {
	    product.ImagePath = product.Site + '/images/brands/' +
	    product.brand +
	    '/' +
	    product.style +
	    '/';
	}

	    // Alternates click handlers
	    $("#alternate-views img").click(function(){
	        ChangeImages(product.selected, $(this).attr('rel'));
	    });


	// Process if Dropdowns template
	$("#config-dropdowns").each(function(){

	    
	    // Click Colour Swatch
	    $("#colors img").each(function(){
                if (!$(this).hasClass('video-swatch')) {
	            $(this).attr("title", $(this).attr("alt")); // Add titles
	            $(this).click(function(){ // Add Clicks
     	                changeColourOption($(this).attr("id"));
	            });
                }
	    });

            // Video swatch
            $('.video-swatch').click(function(){
		$("#btn-video").click();
            });
	    
	    // Colour Option Select click handled
	    $("#config-colour").change(function(){
	        changeColourOption($(this).val());
	    });
	    
	    // Size option Select click handled
	    $("#config-size").each(function(){
	        $(this).change(function(){
	            changeSizeOption($(this).val());
	        });
	        changeSizeOption($(this).val());
	    });
	    
	    

	    
	    $("#add-cart").click(function(e){
		e.preventDefault();
	        validateCart();
	    });

	    var inColour = document.location.toString().split('#')[1];
            if (inColour) {
               if (inColour != 'video') {
                   changeColourOption(inColour);
               } else {
                   $("#btn-video").click();
               }
            }

		// Fix bad page data
		$("#config-colour").each(function(){
		        $(this).empty();
       			$(this).append($('<option>Select Colour...</option>').val(''));
			var $config = $(this);
			var firstColour = '';
			$.each(product.colors,function(key,value){
				if (typeof(value.views) != 'undefined') {
					var $tmp = $('<option/>');
					$tmp.html(value.name);
					$tmp.val(key);
					if (firstColour == '') {
						firstColour = key;
						$tmp.attr('selected','selected');
					}
					$config.append($tmp);
				}
			});
			if (firstColour != '') {
				// append the image that is missing
				if (typeof($("#main_img")[0]) == "undefined") {
					var $a = $('<a/>').attr(
						'href',
						product.ImagePath + product.colors[firstColour].alias + '/image1xxl.jpg')
						.attr('id','myzoom')
						.attr('title',$("#item-name h1").html());
					var $img = $('<img/>').attr(
						'src',
						product.ImagePath + product.colors[firstColour].alias + '/image1xl.jpg')
						.attr('id','main_img')
						.attr('alt',$("#item-name h1").html())
						.attr('title',$("#item-name h1").html())
						.addClass('photo');
					$a.append($img);
					$("#item-img").prepend($a);
				}
				// Fire the option change
				product.selected = '';
				changeColourOption(firstColour);
			}
		});

		
	});
	
	// Department and Search pages
	$('.department').each(function(){
		processSI();
		$(".swatch").each(function() {
			$(this).css("cursor","pointer");
			$(this).click(function() {
				colourClick(this, $(this).parent().attr("id").substring(7));
			});	    
		});
	
	
		//Ajax Paging
		function qaClicks(){
			$("#questions div.pages a.pge").click(function(e){
			    e.preventDefault();
			    var qs = $(this).attr('href').split("?");
			    var catId = 'catId=' + $('body').attr('id');
			    var url = '/community/qa.jsp?';
			    if (qs.length <= 1){
				    window.status=qs[0];
			    	url+= catId;
			    } else {
				    window.status=qs[1];
				    if (qs[1].indexOf('catId') == -1)
				    	url+= qs[1] + '&' + catId;
				    else 
				    	url+= qs[1];
			    }
		    	$("#questions").load(url + ' #questions',function() {
		  		  qaClicks();
		  		  overlayClick();
		    	});	    	
			});
		}
		qaClicks();
		overlayClick();
		$(".cat-options-select").each(function(index, value) {
			var select = $("select",value);
			$("li", select.siblings("ul")).each(function(liIndex, liValue) {
				var a = $("a", liValue);
				select.get(0).options[liIndex + 1] = new Option( a.html() + " (" + liValue.innerHTML.split("(")[1] , a.attr( "href" ) );
			});
			$(value).css("display","block");
		});
		
		// Sort selections handler
		$(".urlSel").change(function(){
			window.location = $(this).val();
		});

	    $(".cat-title-collapsed").click(function(e){
			e.preventDefault();
				if ( $(this).hasClass("cat-title-collapsed")){
					$(this).removeClass("cat-title-collapsed");
					$("#" + this.id + "_content").css("display","block");
				} else {
					$(this).addClass("cat-title-collapsed");
					$("#" + this.id + "_content").css("display","none");
				}
		    });
		$(".cat-title-collapsed").each(function() {
			$(this).css("cursor","pointer");
			$("#" + this.id + "_content").css("display","none");
		});
		
	});
	
	// Basket Page
	$(".basket").each(function(){
        $(".qty").each(function(index, qty) {
            oldQtys[index] = parseInt(qty.value);
        });
        $('form[name=updateForm]').each(function(index, form) {
            $(form).submit(function(){
                $(".qty").each(function(index, qty) {
                    var newVal = parseInt(qty.value);
                    if ( newVal != Number.NaN && newVal != oldQtys[ index ] ){
                        if (newVal > oldQtys[index]){
                            sit.addToBasket(new SITEINTEL.BasketItem( $(qty).parent().attr("name"), qty.id, null, newVal - oldQtys[ index ] ) );
                        } else {
                            sit.removeFromBasket(new SITEINTEL.BasketItem( $(qty).parent().attr("name"), qty.id, null, oldQtys[index] - newVal ) );
                        }
                    }
                });
            });
        });		
	});

});
	
	
// Item Functions - Global


function getAvailText(key){
	for (var i = 0; i < availabilityTable.length; i++){
		if (key == availabilityTable[i].id){
			return availabilityTable[i].label;
		}
	}
	return null;
}

function translateAvailability(sku){
    var translatedText = "";
    translatedText = "";
    if( sku.warehouseLevel > 0 &&  sku.warehouseLevel <= 5){
        translatedText = "2 in stock, ships immediately";
    } else if ( sku.warehouseLevel > 5){
        translatedText = "In stock, ships immediately";
    } else if ( sku.supplierLevel > 0 && sku.supplierLevel <= 2){
        translatedText = "Available by special order. Supplier indicates that this item is currently available but has very limited stock. Subject to availability at time of order. Normally ships within ";
        translatedText+= getAvailText(sku.availability);
    } else if ( sku.supplierLevel > 2 ){
        translatedText = "Available by special order. Normally ships within ";
        translatedText+= getAvailText(sku.availability);
    } else { 
        translatedText = "Sold Out";
    }
    return translatedText;
}


function stopVideo(){
    $("#item-video:visible").each(function(){
        $(this).fadeOut('slow');
	//$("#myzoom").show();
        $f().stop();;
    });
}

function playVideo(){
    $("#item-video:hidden").each(function(){
	//$("#myzoom").hide();
        $(this).show();
	$f().play();
    });
    
}

function changeColourOption(colourId){
    $("#btn-photo").click();
    if (product.selected != colourId) {
		var loading = false;
        // grab config size and empty the contents
        var $sizeSelect = $('#config-size');
        $sizeSelect.empty();
        $sizeSelect.append($('<option>Select Size...</option>').val(''));
        
        // Set the current Colour Swatch
        $("#colors img").removeClass("select");
        
        if (colourId != '') { // Only when the colourId is not blank
            $("#colors #" + colourId).addClass("select");
            ChangeImages(colourId, 0, function(){
                ChangeAlternates(colourId)
            });
            
            // Change the size option
            $.each(product.colors[colourId].skus, function(key,value){
                var $tempOption = $('<option/>');
                $tempOption.html(value.size);
                $tempOption.val(key);
                if (!value.available) {
                    $tempOption.attr('disabled', 'disabled');
                    $tempOption.html($tempOption.html() + ' (Sold Out)');
                }
                $sizeSelect.append($tempOption);
            });
            // Send Tracers
            $.get('/itemViewed/spacer?' + $.param({
				id: colourId,
				type: 'color',
				ai: 'baseColors'
			}));
            sit.sendAdditionalTracer("/si/prdview",$.param({
		'type': 'browse',
		'prd': product.prodId,
		'colour':  colourId,
		'prd-key': product.prodId + "_" + colourId
	     }));

            var url ="/itemFragment/getPersonalisedItems.jsp?" + $.param({
				id: product.prodId,
				categoryId: product.category,
				colourId: colourId
			}); 
            var scroll = false;
			if (!loading && scroll){
				$("#related-items").stop().slideUp('slow', function() {
					$("#related-items-loading").stop().slideDown('slow', function() {
						loading = true;
						$("#related-items").load(url,function() {
							$("#related-items-loading").stop().slideUp('slow', function() {
								$("#related-items").stop().slideDown('slow', function() {
							    });
						    });
							loading = false;
					  	});
				    });
			    });
			} else {
				/*
				$("#related-items").hide();
				$("#related-items-loading").show();
				$("#related-items").load(url,function() {
					$("#related-items-loading").hide();
					$("#related-items").show();
				});
				*/
				$("#related-items-a","#related-items-b").hide();
				$.get(url,function(data){
					var $response = $(data);
					var $ctl = $response.find("#ctl");
					$("#related-items-a").empty();
					$ctl.children().each(function(){
						$("#related-items-a").append($(this));
					});
					var $ymal = $response.find("#ymal");
					$("#related-items-b").empty();
					$ymal.children().each(function(){
						$("#related-items-b").append($(this));
					});
					$("#related-items-a","#related-items-b").show();
				});
			}
        }
        
        // Set the Displayed Colour name
        $("#colors #colour").html((colourId != '') ? product.colors[colourId].name : '');
        
        // Set the Colour option select           
        $("#config-colour").val(colourId);
        
        // Set the current selected colour
        product.selected = colourId;
		
		// Update the price display for size
		changeSizeOption('');
    }
    
}

function ChangeImages(colourId, index, altCallBack){
    stopVideo();

    $("#controls a").each(function(){ $(this).removeClass('selected')});
    $("#btn-photo").addClass('selected');
    
    // Change the Image Over
    var $loading = $('<div/>').addClass('fadeTemplate').html('Loading...');
    $loading.appendTo($('#item-img')).show();

    var views;
    var alias;

    if (typeof product.colors == "undefined") {
        views = product.defaultColourViews;
	alias = product.defaultColourAlias;
    } else {
       views = product.colors[colourId].views;
       alias = product.colors[colourId].alias;
    }
    
    var ipath = product.ImagePath + alias + '/image' + (parseInt(index)+1) + 'xl.jpg';
    var $src = $('<img src="' + ipath + '" />');
    $('#item-img').append($('<div id="item-oth"/>'));
    $src.load(function(){
        $loading.stop().remove();
        $("#item-oth").append($src);
        $("#item-oth").fadeIn('slow', function(){
            if (views[parseInt(index)]) {
                $("#myzoom img").attr('src', ipath)
                $('#myzoom').attr({
                    href: ipath.replace(/xl\.jpg$/, "xxl.jpg"),
                    title: $("#item-name h1").html()
                }).jqzoom(zconfig);
                
            }
            else {
                $("#myzoom img").attr('src', ipath)
                $('#myzoom').unbind().attr({
                    href: 'javascript:void(0)',
                    title: $('#item-name h1').html()
                });
            }
            $("#item-oth").stop().remove();
            if (typeof(altCallBack) != "undefined") 
                altCallBack();
        });
    });
    return true;
    
}

function ChangeAlternates(colourId){
    // Set up alternate views
    var $viewDiv = $('#alternate-views');
    $viewDiv.empty();
    

    //alert(product.colors[colourId].views.length > 1);
    if (product.colors[colourId].views.length > 1) 
	
      //Create the new alternates
      $.each(product.colors[colourId].views, function(index,value){
          var $img = $('<img/>');
          $img.attr({
              src: product.ImagePath + product.colors[colourId].alias +
              '/image' +
              (index+1) +
              's.jpg',
              rel: index
          });
          $img.click(function(){
              ChangeImages(colourId, $(this).attr('rel'));
          });
          $viewDiv.append($img);
      });
    //}
    return true;
}

function changeSizeOption(skuId){

    if (typeof product.colors == "undefined") return;

    var colourId = $("#config-colour").val();
    var sku = {};
    // If a size is not selected, show the range values from the selected colour
    if (skuId != '') {
        sku = product.colors[colourId].skus[skuId];
    }
    else {
        sku = product.colors[colourId].skuRange;
    }
    
    var $priceDiv = $("#price");
    var $clearanceSpan = $("#salePrice");
    var $regularSpan = $("#regularPrice");
    var $addButton = $('#add-cart');
    if (sku.sale.length > 0) {
        if (sku.normal.length > 0) {
            $clearanceSpan.html(product.normalPrefix + " : " + sku.normal);
        }
        else {
            $clearanceSpan.empty();
        }
        if (sku.rrp.length > 0) {
            $regularSpan.html(product.rrpPrefix + " : " + sku.rrp);
        }
        else {
            $regularSpan.empty();
        }
        $priceDiv.html(product.salePrefix + " : " + sku.sale);
        product.price = sku.sale;
        $addButton.show();
    }
    else 
        if (sku.normal.length > 0) {
            $clearanceSpan.empty();
            $priceDiv.html(product.normalPrefix + " : " + sku.normal);
            product.price = sku.normal;
            $addButton.show();
            if (sku.rrp.length > 0) {
                $regularSpan.html(product.rrpPrefix + " : " + sku.rrp);
            }
            else {
                $regularSpan.empty();
            }
        }
        else 
            if (sku.rrp.length > 0) {
                $clearanceSpan.empty();
                $priceDiv.html(product.rrpPrefix + " : " + sku.rrp);
                product.price = sku.rrp;
                $regularSpan.empty();
                $addButton.hide();
            }
    
    // Set availabillity string
    if (skuId != '') {
    	$("#availabilityValue").html(sku.availabilityText);
    } else {
    	$("#availabilityValue").html("&nbsp;");
    }

    // Send tracers
	if (skuId != '') {
		$.get('/itemViewed/spacer?' + $.param({
			id: sku.sizeId,
			type: 'size',
			ai: 'baseSizes'
		}));
	
		sit.sendAdditionalTracer("/si/prdview", $.param({
			type: 'browse',
			prd: product.prodId,
			size: sku.sizeId
		}));
	}

}

function validateCart(){
    if ($("#config-colour").val() == '' || $("#config-size").val() == '') {
        alert("Please select a configuration.");
        return false;
    }
    else {
        var ci = new SITEINTEL.BasketItem( product.prodId, $("#config-size").val(), product.price.substring[1] );
        sit.addToBasket(ci);
        //$("#addToCartForm").submit();
		//var $form = $("#addToCartForm");
		$("#cart-content")
			.hide()
			.stop('true')
			.load(
				"/quickCart.jsp?" +
				$.param({
					productId: product.prodId,
					skuId: $("#config-size").val(),
					quantity: $("#config-qty").val()
				}) + " #minibasket",
				function(){
					$("#ciQty").html($("#biItmCount").html());
					$("#ciValue").html($("#biCartTotal").html());
					$(this).delay(500).slideDown('slow',function(){
						$(this).find('.slotmessage').each(function(){
							$(this).delay(500).slideDown('slow');
						});
					$(this).delay(5000).slideUp('slow');
				}
			);
		});
        return true;
    }
}
    
// Category Functions
function processSI(){
	var crumbString = "";
	var tempString = "";
	$('#crumbs > a').each(function(index, value) { 
		crumbString+= "'" + value.innerHTML.replace("'","\\'") + "':";
	});
	$('#selection-crumbs > a').each(function(index, value) {
		tempString = value.innerHTML.substring( value.innerHTML.indexOf('</span>') + 7 ).replace("'","\\'");
		crumbString+= "'" + tempString + "':";
	});
	//window.status = 'crumb string ' + crumbString;
	var browse = new SITEINTEL.BrowseOTB(crumbString.substring(0, crumbString.length - 1));
	$('.prod-thumb').each(function() {
		var id = $(this).attr("id").substring(6);
		var tempPriceSpan = $('.sale', this.parentNode);
		if ( tempPriceSpan == null || tempPriceSpan.length == 0 ){
			tempPriceSpan = $('.normal', this.parentNode);
		}
		if ( tempPriceSpan == null || tempPriceSpan.length == 0 ){
			tempPriceSpan = $('.retail', this.parentNode);
		}
		if ( tempPriceSpan != null && tempPriceSpan.length > 0 ){
			var priceSpan = $('.price', tempPriceSpan[0]);
			if ( priceSpan != null && priceSpan.length > 0 ){
				browse.addProductView(new SITEINTEL.ProductView(id,priceSpan[0].innerHTML.substring(1),true));
			} 
		}
	});
	sit.opportunityToBuy(browse);	
}


function colourClick(source, mainImg){
    if ($(source).hasClass("select")) 
        return;
    
    var sid = source.id
    if ($(source).hasClass("video")){
    	sid = "video";
    }
    
    $(source).siblings().removeClass("select").end().addClass("select");
    var href = $("#imgLink_" + mainImg).attr('href').replace(/#\w+/, "#" + sid); 
    if (href.indexOf('#') == -1)
    	href+= "#" + sid;	
    $("#imgLink_" + mainImg).attr('href', href);
    $('#hrefLink_' + mainImg).attr('href', href);
    
    var loading = $('.fadeTemplate').clone();
    $(loading).appendTo($("#imgLink_" + mainImg));
    $(loading).show();
	var src = $('<img src="' + $(source).attr('src').replace(/\.gif/,"/image1med.jpg") + '"/>'); 
    $("#thumb_" + mainImg).append($('<div class="img-other" id="tmp_' + mainImg + '" />'));
    $($(src)).load(function(){
        $(loading).remove(); 
        $("#tmp_" + mainImg).append($(src));
        $("#tmp_" + mainImg).fadeIn('slow',function(){
            $("#imgLink_" + mainImg).empty().append($(src));
			$("#tmp_" + mainImg).remove();
        });
    });
	sit.sendAdditionalTracer("/si/prdview", $.param({
		'type': 'browse',
		'prd': mainImg,
		'colour': source.alt,
		'prd-key': mainImg + "_" + source.alt
	}));

	$.get('/itemViewed/spacer?' + $.param({
		id: source.id,
		type: 'color',
		ai: 'baseColors'
	}));

}

function toggleAnswers(questionId){
	$('#tda_' + questionId).slideToggle('slow', function() {
    });
	if ($('#td_' + questionId).hasClass('collapsed')){
		$('#td_' + questionId).removeClass('collapsed');
		$('#td_' + questionId).addClass('expanded');
	} else {
		$('#td_' + questionId).removeClass('expanded');
		$('#td_' + questionId).addClass('collapsed');
	}
}

function toggleAllAnswers(show){
	if (show == true){
		$("td[id^='tda']").each(function(index, value) { 
		    $(value).slideDown('slow', function() {});
		});
		$("td[id^='td_']").each(function(index, value) { 
			$(value).removeClass('collapsed');
			$(value).addClass('expanded');
		});
	} else {
		$("td[id^='tda']").each(function(index, value) { 
		    $(value).slideUp('slow', function() {});
		});
		$("td[id^='td_']").each(function(index, value) { 
			$(value).removeClass('expanded');
			$(value).addClass('collapsed');
		});
	}
}

// Basket Functions
function removeItemFromCart(pid, sid, id) {
    var result = confirm('Do you want to delete item '+ document.getElementById('skuname_'+id).innerHTML + '?');
    if (result) {
        sit.removeFromBasket(new SITEINTEL.BasketItem(pid,sid));
        document.getElementById('itemToRemoveId').value = id;
        document.removeItemForm.submit();
    }
}
function saveCart(){
	if (confirm('If you currently have a saved cart, it will be overwritten. Do you wish to continue?')) {
		document.saveCartForm.submit();
	}
}
