/**
 * plugins.js
 * Collection of functions/actions
 * @author Vincent Bailly
 */

/**
 * check if cookie exists
 * @param	string name The name of the cookie to be found
 * @return	string 'found' if cookie is found, null if not
 */
function getCookie(name) {
  var arg=name+"=";
  var alen=arg.length;
  var clen=document.cookie.length;
  var i=0;
  while (i<clen) {
    var j=i+alen;
    if (document.cookie.substring(i,j)==arg)
      return 'found';
    i=document.cookie.indexOf(" ",i)+1;
    if (i==0) break;
  }
  return null;
}

/**
 * add JQuery Tools Overlay
 * @param	obj arg Params to be passed to Overlay (only "top" here)
 * @return	none
 */
$.fn.addOverlay = function(arg) {
	
	var top = typeof(arg.top)!='undefined'?arg.top:50;
	
	$(this).overlay({
		top: top,
		load: true,
		mask: {
			color: '#000',
			loadSpeed: 0,
			closeSpeed: 0,
			opacity: 0.5
		}
	});
	
};

/**
 * add the WP in a modal window
 * @param	string id The WP container div id
 * @param	string domElem The html dom element to containing the WP
 * @return	none
 */
$.fn.addModalWP = function(id,domElem) {
	
	$("#"+id,$(this)).remove();
	$(this).append(domElem);
	$("#"+id,$(this)).addOverlay({top: "5%"});
	
};

/**
 * on submit run the WP in a modal window
 * @param	obj arg Params to be passed - here: url, id, duration and previousObj (if there is a modal window before)
 * @return	none
 */
$.fn.makeModalWPOnSubmit = function(arg) {
	
	var doSubmit 		= typeof(arg.doSubmit)!='undefined'?arg.doSubmit:'';
	
	$(this).submit(function() {
		
		var url 		= typeof(arg.url)!='undefined'?arg.url:'',
			id 			= typeof(arg.id)!='undefined'?arg.id:'',
		 	duration 	= typeof(arg.duration)!='undefined'?arg.duration:0,
		 	$previous 	= typeof(arg.previousObj)!='undefined'?arg.previousObj:'',
		 	formVars 	= $(this).serialize(),
			wpElem 		= '<div id="'+id+'" class="wp_step2"><img src="' + url + 'resources/images/loader.gif" alt="" style="position:absolute; top:231px; left:298px; z-index:10;" /><iframe src="'+ url + '?' + formVars.replace("isModal=0","isModal=1") +'" width="100%" height="100%" frameBorder="0" allowTransparency="true" style="position:relative; z-index:20; background-color:transparent;">A frames-capable browser is required.</iframe></div>';
		
		if ($previous.length) {
			
			$previous.animate({opacity: 0}, duration, function() {
				$("body").addModalWP(id,wpElem);
			});
			
		} else {
			
			$("body").addModalWP(id,wpElem);
			
		}
		
		return false;
		
	});
		
	if (doSubmit)
		$(this).submit();
	
};

/* end WP */

/**
 * wrap sets of DOM elements (based on http://phpjs.org/functions/array_chunk)
 * @param	string wrap Wrapping element
 * @param	string size Number of elements to be wrapped
 * @return	none
 */
$.fn.makeWrap = function(wrap, size) {
	
	var elements = $(this), x, i = 0, c = -1, l = elements.length, n = [];
	
	for(i; i < l; i++)
		(x = i % size) ? n[c][x] = elements[i] : n[++c] = [elements[i]];
	
	l = n.length;
	for(i = 0; i < l; i++)
		$(n[i]).wrapAll(wrap);
	
}

/**
 * make a DOM elements clickable (or one of its child)
 * @param	object arg Params (link element: for the href - clickElem: to specify the clickable element ($(this) is default))
 * @return	none
 */
$.fn.makeClickable = function(arg) {
	
	var arg 		= typeof(arg)!='undefined'?arg:{};
	var linkElem 	= typeof(arg.linkElem)!='undefined'?arg.linkElem:null;
	var $clickable 	= typeof(arg.clickElem)!='undefined'?$(arg.clickElem,$(this)):$(this);
	var linkUrl 	= $(this).find(linkElem).attr("href");
	
	if (linkUrl) {
		
		$clickable.css({cursor: "pointer"});
		
		$clickable.click(function() {
			window.location = linkUrl;
			return false;
		});
		
	}
	
};

/**
 * detect window size
 * @param	none
 * @return	none
 */
function detectWindowSize()
{
	var pageW = 0,
		pageH = 0;
	
	//Non-IE
	if( typeof( window.innerWidth ) == 'number' ) {
		pageW = window.innerWidth;
		pageH = window.innerHeight;
		
	//IE 6+ in 'standards compliant mode'
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		pageW = document.documentElement.clientWidth;
		pageH = document.documentElement.clientHeight;
		
	//IE 4 compatible
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		pageW = document.body.clientWidth;
		pageH = document.body.clientHeight;
	}
	
	this.w = pageW;
	this.h = pageH;
	
	return false;
}

/**
 * add/remove CSS classes depending on the window size
 * @param	none
 * @return	none
 */
$.fn.adjustWIndowSize = function() {
	
	var pageSize	= new detectWindowSize();
	
	if (pageSize.w <= 1145) {
		$(this).addClass("small_size");
	} else {
		$(this).removeClass("small_size");
	}
	
};

/**
 * hide content
 * @param	string id: html element id
 * @return	none
 */
function hideContent(id) {
	document.getElementById(id).style.display = "none";
}

/* Javascript */
//hideContent('catbanner');

/* JQuery */
$(document).ready(function() {
	
	/* Welcome Programme */
	// init
	//var visit 		= getCookie("ENEWS"),
	//	$wp 		= $("#"+wpId),
	var wpUrl 		= 'http://enews.britishmuseum.org/',
		wpId 		= 'wp_modal',
		$wp 		= '',
		duration 	= 150;
	
	if ($.browser.msie) duration = 0;
	
	/* 2011-05-24: removed due to new cookie regulation (/includes/enewsletter/ removed from homepage too) */
	/* 2011-07-04: put back for google ppc grant (/includes/enewsletter/ added in main/homepage too) */
	/* 2011-12-16: commented out due to ESP switch */
	//if (visit == null) {
	/*if ( $('#r_home').length && !!BMUI.getQueryString( 'enews' )) {
		
		// add cookie
		// commented out due to new cookie regulation
		//var date = new Date();
		//date.setMonth(date.getMonth()+12);
		//document.cookie = ("ENEWS=returning; expires=" + date.toUTCString());
		
		// open the first modal window 
		// not for enews
		//$wp.addOverlay({top: "15%"});
		
		// for google ppc, switch to version 2 and add new source
		var newUrl	= wpUrl+'?isModal=0',
			ppcSrc	= BMUI.getQueryString( 'source' ),
			ppcVer	= BMUI.getQueryString( 'version' );
			
		if (!!ppcSrc)
			newUrl += '&source=' + ppcSrc;
			
		if (!!ppcVer)
			newUrl += '&version=' + ppcVer;
		
		// open the WP in a modal window
		$("#subscribeform",$wp).makeModalWPOnSubmit({previousObj:$wp, url:newUrl, id:wpId, duration:duration, doSubmit:true});
		
	}
	
	// take over from the existing susbscribe form
	$("form.signuptoemailform","#breadcrumb").makeModalWPOnSubmit({previousObj:$wp, url:wpUrl, id:wpId, duration:duration});
	$("form.signuptoemailform","#footer").makeModalWPOnSubmit({previousObj:$wp, url:wpUrl, id:wpId, duration:duration});
	$("form#signuptoemailform","#listing-sidebar").makeModalWPOnSubmit({previousObj:$wp, url:wpUrl, id:wpId, duration:duration});
	$("form#signuptoemailform","#category-emailsignup").makeModalWPOnSubmit({previousObj:$wp, url:wpUrl, id:wpId, duration:duration});*/
	
	/* ================================================================================
	Search
	Author: 	Anthony Ali
				
	Date:		2011-08-24
	Description:Provides robust functionality for storing and replacing text in search box
				Provides cross-domain searching for cms search, collection search and shop online
	================================================================================ */
	$('.searchOptionsToggle').toggle(
		function() {
			$('div.searchOptions ul').fadeIn(800);
			$('.share').parent().parent().find('.shareOptions').fadeOut(400);
			$('.share').parent().removeClass('opened');
			return false;
		},
		function() {
			$('div.searchOptions ul').fadeOut(400);
			return false;
		}
	);

	$('div.searchOptions ul li a').click(function(e) {
		e.preventDefault();
		var searchLocation = $(this).attr('href');
		$('#generalSearch').attr('action', searchLocation);
		var ex = "<input type=\"hidden\" value=\"co_wizr-locayta\" id=\"ex\" name=\"ex\">";
		var template = "<input type=\"hidden\" value=\"wz_locayta\" id=\"template\" name=\"template\">";

		var searchTypeText = $(this).text();

		var exExist = $('#ex');
		var templateExist = $('#template');
		if (exExist.length > 0) {
			exExist.remove();
			templateExist.remove();
		}

		if (searchLocation.indexOf("http://www.britishmuseumshoponline.org/bin/venda") >= 0) {
			$('#siteWideSearch').attr('name', 'q');

			$(ex).appendTo('#generalSearch');
			$(template).appendTo('#generalSearch');
		} else {
			$('#siteWideSearch').attr('name', 'searchText');
		}
		$('div.searchOptions ul li a').removeClass('selected');
		$(this).addClass('selected');

		$('#siteWideSearch').focus();

		var searchText = $('#siteWideSearch').val();

		if (searchText == "Search") {
			searchText = "";
		}
		
		if (searchText != '') {
			$('#siteWideSearch').select();
			$('div.searchOptions ul').toggle();
			$('.headerImageButton').click();
		} else if (searchText == "") {
			$('#siteWideSearch').focus();
			//$('#siteWideSearch').val('Keyword or Product code');
			$('.searchOptionsToggle').click();
		}

		$('.headerImageButton').attr('title', searchTypeText);
		return false;
	});

	// Function for show/hide Search text
	clearDefaultValue = function() {
		var defaultValue = new Array();
		$("input[type!='submit']").focus(function() {
			if (!defaultValue[this.id]) {
				defaultValue[this.id] = this.value;
			}
			if (this.value == defaultValue[this.id]) {
				this.value = '';
			}
			$(this).blur(function() {
				if (this.value == '') {
					this.value = defaultValue[this.id];
				}
			});
		});
	}
	$('input.button').mouseover(function() {
		$(this).addClass('hover');
	});
	$('input.button').mouseout(function() {
		$(this).removeClass('hover');
	});
	/* ================================================================================
	End
	================================================================================ */
	
	/* Move BM logo depending on window size */
	$("#wrapper").adjustWIndowSize();
	
	$(window).resize(function() {
		$("#wrapper").adjustWIndowSize();
	});
	
	/* Jquery scrollable cross-sells */
	var $scrollable	= $("#xsells"),
		itemNb	= 6;
	
	if ( $("body").attr("id") == "r_home" || $("body").attr("id") == "r_tickets" || $("body").attr("id") == "r_art_prints" || $scrollable.hasClass("emptybasket") )
		itemNb	= 8;
	
	if ($scrollable.length) {
		if( typeof( LM ) == 'undefined' ) LM = {};
		LM.complete(function() {
			$("div.list_item",$scrollable).makeWrap('<div class="jwrapper"></div>',itemNb);
			$("div.jscrollable",$scrollable).css({overflow:"hidden"}).scrollable({circular:true, mousewheel:true});
		});
	}
	
	/* Jquery tabs for product page */
	 $("div.jtabbar","div.tabs_view").tabs(".jtabs .list_item");
	
	/* jScrollPane */
	 /*$(".jscrollpane","#product_info").jScrollPane({
		verticalDragMinHeight:10,
		verticalDragMaxHeight:100
	});*/
	
	/* Product listing pagination */
	$listingcontext = $("#listing-context","#content");
	if ($listingcontext.length && !$("#wrapper").hasClass("l_search")) {
		$(".product-listing-pagination li a",$listingcontext).live("click",function() {
			$listingcontext.prepend('<div class="loading_screen"></div><div class="loading_img"><img src="/content/ebiz/britishmuseumonlineshop/resources/img/ajax-loader2.gif" alt="Loading" /></div>');
			
			$.get(this.href, function(data) {
				$data = $("#listing-context",$(data));
				$listingcontext.html($data.html());
				BMUI.ProductListing.init();
			});
			
			return false;
		});
	}
	
	/* Find by dropdown submit */
	$findby_container = $("#listing_findby","#content");
	if ($findby_container.length) {
		$findby_container.show();
		$('select',$findby_container).change(function() {
			top.location = BMUI.Page.webroot_absolute + $(this).val();
		});
	}
	
	/* newsletter icon */
	$("#breadcrumb-signup-hit","#breadcrumb").click(function() {
		return false;
	});
	
	/* Promotion pages */
	// Xmas 2010
	/*var $xmasWrapper = $("#xmas_wrapper");
	
	// replace underscore with space in link titles
	$(".prod_item li.view_all a",$xmasWrapper).each(function() {
		$(this).attr("title",$(this).attr("title").replace(/_/gi, " "));
	});
	
	// make div clickable
	$("#xmas_categories .list_item",$xmasWrapper).each(function() {
		var $prodItem = $(".prod_item",$(this));
		$prodItem.append('<div class="dummy"></div>');
		var $dummy = $(".dummy",$(this));
		$dummy.css({position:"absolute", top:60, left:0, width:250, height:115});
		
		$("div.prod_item",$(this)).makeClickable({linkElem:"a:first", clickElem:"div.prod_info"});
		$("div.prod_item",$(this)).makeClickable({linkElem:"a:first", clickElem:"div.dummy"});
		$("p.list_item_heading",$(this)).makeClickable({linkElem:"a:first"});
	});
	
	$("#xmas_top_10 .list_item",$xmasWrapper).each(function() {
		$("div.prod_item",$(this)).makeClickable({linkElem:"a:first"});
	});
	
	// jquery tools scrollable
	$("div.list_item","#xmas_wrapper #xmas_top_10").makeWrap('<div class="jwrapper"></div>', 5);
	$("div.jscrollable",$xmasWrapper).css({overflow:"hidden"}).scrollable({circular:true, mousewheel:true});*/
	
	// Winter Sale 2010 landing page
	/*var $wrapperWS	=	$("#r_winter_sale #inner_content"),
		$jtoolsWS	=	$("#bestsellers_pane",$wrapperWS);
	
	$("div.list_item",$wrapperWS).each(function() {
		$("div.prod_item",$(this)).append('<div class="dummy"></div>');
		$("div.dummy",$(this)).css({position:"absolute", top:40, left:0, width:'100%', height:210});
		$("div.prod_item",$(this)).makeClickable({linkElem:"li.book_now a", clickElem:"div.dummy"});
	});
		
	$("div.list_item",$jtoolsWS).each(function() {
		$("div.prod_item",$(this)).makeClickable({linkElem:"a:first"});
	});
	
	$("div.list_item",$jtoolsWS).makeWrap('<div class="jwrapper"></div>', 5);
	$("div.jscrollable",$jtoolsWS).css({overflow:"hidden"}).scrollable({circular:true, mousewheel:true});*/
	
	// Valentines 2011
	//var $wrapperV	=	$("#r_valentines #inner_content");
	
	// Mothers day 2011
	var $wrapperV	=	$("#r_mothers_day #inner_content");
	
	// Fathers day 2011
	//var $wrapperV	=	$("#r_fathers_day #inner_content");
	
	// Summer sale 2011
	//var $wrapperV	=	$("#r_summer_sale #inner_content");
	
	// Xmas 2011
	//var $wrapperV	=	$("#r_christmasshop #inner_content");
	
	if ($wrapperV.length)
	{
		var $jtoolsV	=	$("#bestsellers_pane",$wrapperV);
		$("div.list_item",$jtoolsV).makeWrap('<div class="jwrapper"></div>', 5);
		$("div.jscrollable",$jtoolsV).css({overflow:"hidden"}).scrollable({circular:true, mousewheel:true});
	}
	
});
