/* 
 * 
 * 
 */

var dialog = jQuery('<div id="MB_Container"></div>');
var jspApi;
var mbH;

jQuery(document).ready(function(){	
	
	 if(jQuery.isFunction( dialog.dialog )) {
		  dialog.dialog({ 
		   bgiframe: true,
		   autoOpen: false,
		   draggable: false,
		   zIndex: 9999,
		   buttons: {},
		   modal: true,
		   resizable: false,
		   height: 'auto', width: 'auto',
		   close: function(event, ui) { jQuery('html').css('overflow', 'auto'); }
		  });
		
		// Universal create modal box function for A tags
		jQuery('a.modalBox').each(function() {
			jQuery(this).bind('click', function() {
				modalBoxCreate(this.href);
				return false;
			})
		});
		
		// Tell A friend button handler
		jQuery('#tellafriend').click(function(){
			var browserAvailHeight = jQuery(window).height();
			var mbH = browserAvailHeight - 70;
			mbH = ( mbH > 550 ) ? 550 : mbH; // 550px max height for tellafriend overlay 
			var mbW = 556; // 556px fixed width for tellafriend overlay
	
			modalBoxCreate(this.href + '&mbW=' + mbW + '&mbH=' + mbH + '&width=' + mbW, "jspSendToFriend");
	
			return false;
			
		});
		
		// Size Guide link handler
		jQuery('a.sizeGuideLink').bind('click', function() {
				
			var browserAvailHeight = jQuery(window).height();
			var browserAvailWidth = jQuery(window).width();

			var mbHeight = browserAvailHeight*0.85 - 130;
		
			var ajaxRequestURL = this.href + '&height='+mbHeight;
			
			modalBoxCreate(ajaxRequestURL, 'jspSizeGuide');
			
				return false;
		});
		
		// Wash Guide link handler
		jQuery('a.washGuideLink').bind('click', function() {
				
			var browserAvailHeight = jQuery(window).height();
			var browserAvailWidth = jQuery(window).width();

			var mbHeight = browserAvailHeight*0.60;
		
			var ajaxRequestURL = this.href + '&height='+mbHeight;
			
			modalBoxCreate(ajaxRequestURL, 'jspSizeGuide');
			
				return false;
		});
		
		// Quick buy link handler
		jQuery(document).on('click', '.quickBuyLink', function() {

			var browserAvailHeight = jQuery(window).height();
			mbH = browserAvailHeight - 80;
			mbH = ( mbH > 645 ) ? 645 : mbH;
			var mbW = 830;

			modalBoxCreate(this.href + '&height=645&width=' + mbW + '&mbW=' + mbW + '&mbH=' + mbH, "msDropDownApply");

			return false;		
		});
	
		// Show large product images 
		jQuery('a#fullscreen').click(function(){
			var currentImgSrc = jQuery('#prodImg').attr('src');
			
			var srcBeforeAmp = currentImgSrc.split('?')[0];
	
			var indexBeforeImgId = srcBeforeAmp.lastIndexOf('/')+1;
	
			var imgId = srcBeforeAmp.substring(indexBeforeImgId);
			
			var browserAvailHeight = jQuery(window).height();
			var browserAvailWidth = jQuery(window).width();

			var wW = browserAvailHeight - 50; // 50px for top and bottom space
			
			var wH = wW - 20;
			wW = ( wW < 600 ) ? 600 : wW;  // 600px minimum width for image fullscreen overlay
			var iW = wW - 115;
			var iH = iW;

			var mbH = wH
			var mbW = wW;
			
			var mbHeight = iW
			var mbWidth = wW;
			
			var ajaxRequestURL = this.href + '&curProdImg=' + imgId + '&height='+mbHeight + '&width='+mbWidth + '&mbW=' + mbW + '&mbH=' + mbH;
			modalBoxCreate( ajaxRequestURL );
			
			return false;
			
		});
		
		jQuery('.errorMessage:last').hide();
		jQuery('.errorMessage:last').removeClass('hidden');
		
		jQuery(window).resize(function () {
			if ( dialog.dialog("isOpen") )
			{
				dialog.dialog("option","position","center");
			}
		});
		
	}
	
	jQuery('ul#mainNav').find('li.tabLevel').each(function() {
		var l2Category = jQuery(this);
		l2Category.hover(function(){
			
			var l2Categories = l2Category.children('.leftMenuShadow');
			
			var menuX = l2Category.parent().parent().offset().left;
			var menuWidth = l2Category.parent().parent().outerWidth(true);
			var menuCenter = menuX + Math.floor(menuWidth/2);
			var menuRigtX = menuX + menuWidth;
			
			var l2CategoryX = l2Category.offset().left;
			var l2CategoryWidth = l2Category.outerWidth(true) + 6;
			var l2CategoryCenter = l2CategoryX + Math.floor(l2CategoryWidth/2);
			var l2CategoryRightX = l2CategoryX + l2CategoryWidth;
			
			var l2CategoriesX = l2Category.children('.leftMenuShadow').offset().left;
			var l2CategoriesWidth = l2Category.children('.leftMenuShadow').outerWidth(true);
			var l2CategoriesCenter = l2CategoriesX + Math.floor(l2CategoriesWidth/2);
			var l2CategoriesRightX = l2CategoriesX + l2CategoriesWidth;
			
			
			var categoryOffset = menuCenter - l2CategoryX;
			var categoriesOffset = l2CategoryCenter - l2CategoriesCenter;
			var availableSpace = menuRigtX - l2CategoriesRightX;
			
			var newL2CategoriesX = l2CategoriesX;
			if(l2CategoriesWidth < menuWidth + 6) {
				if(categoriesOffset > 0) {
					var currentLeft = parseInt(l2Categories.css('left'), 10);
					if(categoriesOffset < availableSpace) {
						l2Categories.css('left', currentLeft + categoriesOffset);
					} else {
						l2Categories.css('left', currentLeft + availableSpace);
					}
				}
			}
			
			
			l2Category.children('.leftMenuShadow').outerWidth();
		}, function(){
			
		});
	});
	
	if (typeof cmEnabled != 'undefined' && cmEnabled == true) {
		// Send Page Element tag on click on different carousel elements (tabs, left arrow, right arrow, product, view full range link)
		jQuery('.tabbed_area .tabs li a').bind('click', function() {
			contentAssetID = jQuery(this).parent().parent().parent().find("span.contentAssetID").attr("id");
			var contentAsset = (contentAssetID!=""?contentAssetID:jQuery(this).text());
			cmCreatePageElementTag(jQuery(this).text(), contentAsset, "", "", "", "");
		});
		jQuery('.tabbed_area .slideLeft').bind('click', function() {
			sendCMElementTag.call(this, "Left Arrow");
		});
		jQuery('.tabbed_area .slideRight').bind('click', function() {
			sendCMElementTag.call(this, "Right Arrow");
		});
		jQuery(document).on('click', '.tabbed_area .listItem a[class!=quickBuyLink]', function() {
			var elementID = jQuery(this).parents('.listItem').find('input[name=pid]').val();
			sendCMElementTag.call(this, elementID);
		});
		jQuery('.tabbed_area .viewAll_carousel').bind('click', function() {
			cmCreatePageElementTag("View the full range", jQuery(this).parents('.tabbed_area').find('.tabs li.active a').text(), "", "", "", "");
		});
		
		getElementCategory = function(element) {
			var elementCategory = jQuery(element).parents('.tabbed_area').find('.tabs li.active a').text();
			if (elementCategory.trim() == "") {
				elementCategory = jQuery(element).parents('.tabbed_area').find('h3').text();
			}
			return elementCategory;
		}

		sendCMElementTag = function(elementID) {
			var elementCategory = getElementCategory(this);
			cmCreatePageElementTag(elementID, elementCategory, "", "", "", "");
		}
	}

});

function submitSF(form) {

	var serializedFormData = jQuery(form).serialize();
	var containerToUpdate = 'MB_Container';

	jQuery.ajax({
		   type: "POST",
		   url: form.action,
		   data: serializedFormData,
		   success: function(msg){
		     jQuery('#MB_Container').html(msg);
		   },
		   error : function() {
			   alert("Server error! Please close this window and press ESC key to continue!");
		   }
		 });
	
	return false;
}

function jspSizeGuide() {
	var jsp = jQuery('div.modalBoxContent div.tabContents').jScrollPane({
		showArrows: true,
		verticalDragMinHeight: 49,
		verticalDragMaxHeight: 49,
		contentWidth: 400
	});
	jspApi = jsp.data('jsp');
}

function jspAddToBasketOverlay() {
	jQuery('div#addToBasketOverlay.scroll').jScrollPane({
		showArrows: true,
		verticalDragMinHeight: 49,
		verticalDragMaxHeight: 49,
		contentWidth: 400,
		autoReinitialise: true
	});
}

function jspSendToFriend() {
	jQuery('div#sendToFriend').jScrollPane({
		showArrows: true,
		verticalDragMinHeight: 49,
		verticalDragMaxHeight: 49,
		contentWidth: 400
	});
}
	
// Variation selection drop down  method for quickbuy
function msDropDownApply()
{
	jQuery(".jsHidden").removeClass('jsHidden');
	$('form.jNice').form();
	jQuery('div#quickBuyDialog.scroll').jScrollPane({
		showArrows: true,
		verticalDragMinHeight: 49,
		verticalDragMaxHeight: 49,
		contentWidth: 400,
		arrowButtonSpeed: 50,
		autoReinitialise: true
	});
}

//ModalBox construction and ajax request.
function modalBoxCreate( ajaxRequestTarget, funcOnComplete, addModalBoxHtml)
{
	jQuery('html').css('overflow', 'hidden');
	jQuery('html').bind('keypress', function(e)
	{
		var k = e.keyCode;
		if(k >= 37 && k <= 40 || k == 33 || k == 34)
		{
		   return false;
		}
	});
	
	var queryParameters = parseQuery(ajaxRequestTarget.replace(/^[^\?]+\??/,''));

	if(queryParameters["width"] != null) {
		dialog.dialog("option", "width", parseInt(queryParameters["width"]) + 50); // + 50px modalBox shadows sizes
	} else {
		dialog.dialog();
	}
	
	var browserAvailHeight = jQuery(window).height();
	var browserAvailWidth = jQuery(window).width();
	var MB_loaderTop = Math.round( ( browserAvailHeight - 186 ) / 2 );
	var MB_loaderLeft = Math.round( ( browserAvailWidth - 148 ) / 2 );
	
	jQuery("body").append('<div id="MB_loader"><img src="' + loaderImage + '" /></div>');
	
	jQuery('#MB_loader').css('top', MB_loaderTop + 'px');
	jQuery('#MB_loader').css('left', MB_loaderLeft + 'px');
	
	jQuery("body").append("<div id='loaderOverlay' style='height: 100%;left: 0;position: fixed;top: 0;width: 100%;z-index: 9999; background: #dddddd; opacity: .75;filter:Alpha(Opacity=75);'></div>");
	jQuery('#loaderOverlay').show(); 

	jQuery.get(ajaxRequestTarget, function(response, status, xhr){
			jQuery('#MB_loader').remove();
			jQuery('#loaderOverlay').remove();
		
		if (status == "error") {
			alert("Server error! Please close this window to continue!");
		} else {
			if (addModalBoxHtml) {
				jQuery(dialog).html(modalBoxWrapperHtml);
				jQuery(dialog).find('#MB_header').after('<div id="MB_Background" />');
				
				var mbW = browserAvailWidth;
				var mbH = browserAvailHeight - 80;
				
				if(queryParameters["width"] != null) {
					mbW = Math.min(parseInt(queryParameters["width"]) + 50, browserAvailWidth);
				}
				mbW = ( mbW > 830 ) ? 830 : mbW;
			
				if(queryParameters["height"] != null) {
					mbH = Math.min(parseInt(queryParameters["height"]), browserAvailHeight - 80);
				}
				mbH = ( mbH > 645 ) ? 645 : mbH;

				jQuery('#MB_Background')
					.css({
						'backgroundColor': '#ffffff',
						'width': mbW-46,
						'max-height': mbH,
						'overflow' : 'auto'
					}).append('<a href="#" class="hide">&nbsp;</a>')
					.append(response);
				dialog.dialog("open");
			} else {
				dialog.dialog("open");
				jQuery(dialog).html(response);
			}
			dialog.dialog({
							position: "center",
							width: mbW
						});
				
			jQuery('#MB_Background').jScrollPane({
							showArrows: true,
							verticalDragMinHeight: 49,
							verticalDragMaxHeight: 49,
							contentWidth: 5,
							hijackInternalLinks: true,
							hideFocus: true,
							autoReinitialise: true,
							maintainPosition: false
			});
			
			if ( funcOnComplete != null ) {
				window[funcOnComplete]();
			}
		}
	});
}

function parseQuery ( query ) 
{
   var Params = {};

   if ( !query ) 
   {
	   return Params;
   }
   
   var Pairs = query.split(/[;&]/);
   
   for ( var i = 0; i < Pairs.length; i++ ) 
   {
      var KeyVal = Pairs[i].split('=');
      
      if ( ! KeyVal || KeyVal.length != 2 ) 
      {
    	  continue;
      }
      
      var key = unescape( KeyVal[0] );
      
      var val = unescape( KeyVal[1] );
      
      val = val.replace(/\+/g, ' ');
      
	  Params[key] = val;
   }
	   
   return Params;
}

function initVideoContainer( flashPlayer, skinFile, videoURI, video360URI )
{
	jQuery('a#video').click(function() {

		jQuery("div#imagesContainer").hide();
		jQuery("div#video360Container").hide();
		jQuery("div#videoContainer").show();
		
		var videoId = jQuery('#productVideoId').html();

		// Check if browser has flash enabled.       
        if ( !hasFlash() )
        {
        	jQuery('#videoPlayer').html(jQuery('#noFlash').html());
        	
        	return false;
        }
         
        jwplayer('videoPlayer').setup({
			'flashplayer': flashPlayer,
		    'file': videoId,
		    'streamer': videoURI,
		    'autostart': true,
		    'controlbar': 'bottom',
			'skin': skinFile,
			'height': 390, 
			'width': 300
		  });

        return false;		
	});

	jQuery("a.backToImagesText").click(function() {

		jQuery("div#videoContainer").hide();
		jQuery("div#video360Container").hide();

		if ( hasFlash() && typeof jwplayer() != 'undefined' ) 
		{
			jwplayer().stop();
		}
	
		jQuery("div#imagesContainer").show();
		
		return false;		
	});

	jQuery("a#video360").click(function() {
		
		jQuery("div#videoContainer").hide();
		jQuery("div#imagesContainer").hide();
		jQuery("div#video360Container").show();

		// Check if browser has flash enabled.       
        if ( !hasFlash() )
        {
        	jQuery('#video360Player').html(jQuery('#noFlash').html());
        	
        	return false;
        }
		
        jQuery('p#instructions360').removeClass('hidden');
		
        var videoId = jQuery('#product360VideoId').html();
		
		var html =	'<object id="AAsdaAsda/test_spinset01" width="300" height="382" align="" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,65,0" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000">';
			html +='<param value="' + video360URI + '" name="movie">';
			html +='<param value="asset=' + videoId + '" name="flashvars">';
			html +='<param value="true" name="fullScreenOnSelection">';
			html +='<param value="false" name="menu">';
			html +='<param value="high" name="quality">';
			html +='<param value="opaque" name="wmode">';
			html +='<param value="noscale" name="scale">';
			html +='<param value="LT" name="salign">';
			html +='<param value="true" name="allowFullScreen">';
			html +='<param value="#FFFFFF" name="bgcolor">';
			html +='<param value="always" name="allowScriptAccess">';
			html +='<embed width="300" height="382" pluginpage="http://www.macromedia.com/go/getflashplayer" allowfullscreen="true" menu="false" type="application/x-shockwave-flash" name="AAsdaAsda/test_spinset01" flashvars="asset=' + videoId + '" swliveconnect="true" bgcolor="#FFFFFF" quality="high" wmode="opaque" allowscriptaccess="always" fullscreenonselection="”true”" src="' + video360URI + '">';
			html +='</object>';
			
		jQuery("#video360Player").html(html);

		return false;		
	});
}

function videoOnOverlay( flashPlayer, skinFile, videoURI, height, width, videoId, videoContainer )
{
	jwplayer( videoContainer ).setup({
		'flashplayer': flashPlayer,
	    'file': videoId,
	    'streamer': videoURI,
		'controlbar': 'bottom',
		'skin': skinFile,
		'heigh': height, 
		'width': width
	  });
}

function watchVideoClick()
{
	
	jQuery('.activeSGContent .howToMeasure:last').toggleClass('hidden');
	jQuery('.activeSGContent .videoPlayerSG:last').toggleClass('hidden');

	var videoContainer = jQuery('.activeSGContent .videoPlayerSG:last');
	
	var videoHeight = videoContainer.find('.videoHeight:last').html();
	var videoWidth = videoContainer.find('.videoWidth:last').html();
	var videoFilePath = videoContainer.find('.videoFilePath:last').html();
	var videoPlayerContent = videoContainer.find('.videoPlayerContent:last');

	var videoPlayerContentId = "videoPlayer_" + Math.floor( Math.random(1,100) * 11 );
		
	while( jQuery('.sizeGuideTab_content #' + videoPlayerContentId ).length )
	{	
		videoPlayerContentId = "videoPlayer_" + Math.floor( Math.random(1,100) * 11 );	
	}

	videoPlayerContent.attr('id',videoPlayerContentId);
	
	videoOnOverlay( flashPlayer, skinFile, videoURI, videoHeight, videoWidth, videoFilePath, videoPlayerContentId );			
	
}

function assetLinkClick( assetLinkHref )
{
	var queryParameters = parseQuery(assetLinkHref.href.replace(/^[^\?]+\??/,''));

	if ( queryParameters["reqasset"] == null ) 
	{
		return false;
	}

	var assetId = queryParameters["reqasset"];

	var activeSGContent = jQuery('.activeSGContent:last');
	
	var newActiveSGContent = jQuery('.' + assetId + ':last').html();

	activeSGContent.html(newActiveSGContent);
}

function bvLoadRR(pid, bvServer, version) {
	var ver = (version != undefined) ? version : '';
	// Start Configuration
    var bvPage = bvServer + '/1440george' + ver + '-en_gb/' + pid + '/reviews.htm?format=embedded';
    var URLParamNames = {
        reviewID : 'featurereview',
        reviewPage : 'reviewspage'
    };
    // End Configuration
    
    var getURLParam = function(name) { 
        if (!name) return null;
        var match = (new RegExp('[?&]' + name + '=([^&#]+)')).exec(window.location.search);
        return match ? decodeURIComponent(match[1]) : null;        
    };
    
    bvReviewID = getURLParam(URLParamNames.reviewID);
    bvReviewPage = getURLParam(URLParamNames.reviewPage);
    
    if (/^[0-9]+$/.test(bvReviewID)) {
        bvPage += '&reviewid=' + bvReviewID;
    } else if (/^[0-9]+$/.test(bvReviewPage)) {
        bvPage += '&page=' + bvReviewPage;
    }
    
    document.getElementById('BVFrame').src = bvPage;
    
}

function watchVideoClickSimple() {

	if ( jQuery('#videoContainerSP').length > 0 ) 
	{
	var videoContainer = jQuery('#videoContainerSP');
	
	var videoHeight = videoContainer.find('.videoHeight:last').html();
	var videoWidth = videoContainer.find('.videoWidth:last').html();
	var videoFilePath = videoContainer.find('.videoFilePath:last').html();
	var videoPlayerContent = videoContainer.find('#videoPlayerSP').attr('id');
	var videoPreview = videoContainer.find('.videoPreview').html();
	
    jwplayer( videoPlayerContent ).setup({
		'flashplayer': flashPlayer,
		    'file': videoFilePath,
	    'streamer': videoURI,
		'image': videoPreview,
		'controlbar': 'over',
		'skin': skinFile,
		'height': videoHeight, 
		'width': videoWidth
	  });
	}
}

function hasFlash()
{
	// Check browser type (IE or Other)
	var p = navigator.plugins;
	var isie = (p && p.length) ? false : true; 

	var flashversion = function() {
		
		if ( isie )
		{
			var key = 'ShockwaveFlash.ShockwaveFlash';
			
			try 
			{
				var axo = new ActiveXObject(key+'.7');
			} 
			catch(e) 
			{
				try 
				{
					var axo = new ActiveXObject(key+'.6');
					return [6, 0, 21];
				} 
				catch(e) {};
				
				try 
				{
					axo = new ActiveXObject(key);
				} 
				catch(e) {};
			}
			
			if (axo != null) 
			{
				return axo.GetVariable("$version").split(" ")[1].split(",");
			}
		} 
		else 
		{
			var p = navigator.plugins;
			var f = p['Shockwave Flash'];
	
			if ( f && f.description ) 
			{
				return f.description.replace(/([a-zA-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split(".");
			} 
			else if ( p['Shockwave Flash 2.0'] ) 
			{
				return '2.0.0.11';
			}
		}
	};
	
	return ( flashversion() ) ? true : false;	
}
