﻿/**
* @author Jerome Conde <j.conde@impactbbdo.ae>
*/
$(function(){
	//global vars
	var locale = "en_gb", $pageWrap = $("div.PageWrap"), $page = $("div.Page");
	if(window.location.href.indexOf("ar_ae") > -1) locale = "ar_ae";

	var isIE = $.browser.msie;
	var isIE6 = isIE && ($.browser.version == 6.0);
	var isIE7 = isIE && ($.browser.version == 7.0);
	
	var swfEnabled = false;
	swfEnabled = typeof swfobject == "object" && swfobject.hasFlashPlayerVersion("8.0");
	
	if(typeof assetPath == "undefined") assetPath = "";
	
	//add 'FirstChild' and sfhover class for ie6 */
	var firstChild = function(){
		$("li:first-child").addClass("FirstChild");
	}
	var lastChild = function(){
		$("li:last-child").addClass("LastChild");
	}
	if($.browser.msie && $.browser.version == "6.0") {
		firstChild();
	}
	// add LastChild class to IE
	if($.browser.msie){
		lastChild();
	}
	
	// cufon implementation
	if(typeof Cufon != "undefined" && locale == "en_gb"){
		Cufon.replace("div.Col2 h2",{fontFamily:'TradeGothic',fontSize:'30px',letterSpacing:-1})
		("div.CareerBanner h3",{fontFamily:'TradeGothic',fontSize:'24px',letterSpacing:-1});
	}
	
	//auto text handler
	$("#QuickSearch input.AutoText")
	.each(function(){
		var autoText = "";
		var defaultText = $(this).val();
		$(this).bind('focus',function(){
		autoText = $(this).val();
		if(autoText == defaultText) $(this).val("");
		})
		.bind('blur',function(){
			if($(this).val() == "")
			$(this).val(defaultText);
		});
	});
	//Quick search to submit on Enter key press
	$("#QuickSearch input[type=text]").bind('keypress',function(e){
    		if(e.which == 13) $(this).next('a').click();
  	});


	//external links
	$("a[rel=external],a[rel=External]").click(function(){
		$(this).attr('target','_blank');
	});
	
	// Content Main image fix
	$("div.Copy>img:first").addClass("CopyKeyImage");
	
	// Boxes removed
	$("#Box-8,#Icon-8").remove();
	
	// Initially loaded boxes
	$("#ModuleWrapper").find(".Module").removeClass('Loaded')
	.filter("#Box-0,#Box-1,#Box-2,#Box-4,#Box-5,#Box-6").addClass('Loaded').css({display:'inline'});
	
	
	//create box order pattern
	var readSequence = function(){
		var _seq = "";
		$("#ModuleWrapper .Sortable").each(function(){
			var _id = $(this).attr('id').split('-')[1];
			_seq += _id+'.';
		});
		return _seq;
	}
	
	// save sequence to cookie
	var saveSequence = function(){
		var _seq = readSequence();
		eraseCookie('box-sequence');
		createCookie('box-sequence',_seq,24);
	}
	
	// get sequence from cookie
	var getSequence = function(){
		return readCookie('box-sequence');
	}
	
	// Module/Box handler
	$("#ModuleWrapper").each(function(){
		var $me = $(this), $fixed = $me.find('.Fixed');
		$me.sortable({
			items:'.Sortable',
			containment:'body',
			handle:'h2',
			tolerance:'pointer',
			opacity:.6,
			placeholder:'ui-placeholder',
			stop:function(){
				// save sequence to cookie
				saveSequence();
			}
		});
		
		// attach close button
		$me.find('div.Sortable:not(.Fixed)').each(function(){
			var $t = $(this), _id = $t.attr('id'), $close = $("<span class='Close' />");
			$close.appendTo(this).click(function(){
				unloadBox($t,function(){
					//todo: update sequence in cookie
				});
			});
			//if cookie is not set
			var _cookie = getSequence();
			if(!_cookie){
				if($t.hasClass('Loaded')){
					$("#"+_id.replace('Box','Icon')).addClass('Loaded');
				}
			}
			
		});
		
		// disable fixed icon
		$me.find('div.Sortable.Fixed').each(function(){
			var _id = parseInt($(this).attr('id').split('-')[1]);
			$("#Icon-"+_id).addClass('Loaded');
		});
		
		// create bin for unloaded boxes
		$me.after("<div id='ModuleBin' />");
		var $bin = $("#ModuleBin");
		
		// unload box
		var unloadBox = function($box,fn){
			$box.hide(300,function(){
				var _id = "#"+$box.attr('id').replace('Box','Icon');
				$box.appendTo($bin);
				
				// update icon states in the Panel
				$("#WBox").find(_id).removeClass('Loaded');
				updateWBox();
				if(fn) fn();
			});
		}
		
	});
	
	//arrange boxes in a given sequence
	var arrangeBoxes = function(strSeq){
		$("div.Sortable").css({display:'none'}).appendTo($("#ModuleBin"));
		$("#WBox .Panel li").removeClass('Loaded');
		var _seq = strSeq.split('.');
		for(var i=0; i < _seq.length-1; i++){
			$("#Box-"+_seq[i]).css({display:'inline'}).appendTo($("#ModuleWrapper"));
			$("#Icon-"+_seq[i]).addClass('Loaded');
		}
		//Show hidden fixed Boxes
		$("div.Fixed").not(":visible").css({display:'inline'}).appendTo($("#ModuleWrapper"));
	}
	if(getSequence()) arrangeBoxes(getSequence());
	
	// WBox handler
	var $WBox = $("#WBox");
	var updateWBox = function(){
		$WBox.find("li:not(.Loaded) img").each(function(){
			var _img = $(this).attr('src');
			_img = _img.replace('/Disabled/','/Active/');
			$(this).attr('src',_img);
			
			var _id = $(this).parents('li').attr('id').replace('Icon','Box');
			if($("#ModuleWrapper #"+_id).length){
				$("#"+_id).css({display:'none'}).appendTo($("#ModuleBin"));
			}
						
		}).end()
		.find("li.Loaded img").each(function(){
			var _img = $(this).attr('src');
			_img = _img.replace('/Active/','/Disabled/');
			$(this).attr('src',_img);
		});
		
		// save sequence to cookie
		saveSequence();
	}
	
	// Load Box
	var loadBox = function(strID){
		$("#"+strID).insertBefore($("#ModuleWrapper .Sortable:first")).show(400);
		//todo: read sequence again
		//todo: save sequence to cookie
	}
	
	$WBox.hover(
		function(){
			var $me = $(this).addClass('Hover');
			var $panel = $me.find('.Panel');
			$panel.fadeIn(300);
		},
		function(){
			var $me = $(this).removeClass('Hover');
			var $panel = $me.find('.Panel');
			$panel.fadeOut(100);
		}
	)
	.each(function(){
		var $wbox = $(this), $panel = $wbox.find('.Panel');
		var $li = $panel.find("li"), $liOdd = $panel.find("li:odd").addClass('Odd');
		
		// assign Hover class
		$li.find('a').hover(function(){
			$(this).addClass('Hover');
			//make sure all tooltip texts will not wrap down
			var $span = $(this).find('span');
			if($span.hasClass('Adjusted')) return;
			if($span.height() > 14){
				var _w = $span.width();
				$span.width(_w + 15);
			}
			$span.addClass('Adjusted');
		},function(){$(this).removeClass('Hover');})
		// icons click handler
		.click(function(){
			var $t = $(this),_id = $t.parent().attr('id');
			if($t.parent().hasClass('Loaded')) return false;
			_id = _id.replace('Icon','Box');
			loadBox(_id);
			$t.parent().addClass('Loaded');
			updateWBox();
			return false;
		})
		// adjust tooltip text widths
		.find('span').each(function(){
			var $t = $(this), _text = $t.text(), _len = _text.length;
			var _re = /[I,\']/g; _m = _text.match(_re) ? _text.match(_re) : [];
			var _re2 = /[T,L]/g; _m2 = _text.match(_re2) ? _text.match(_re2) : [];
			_len -= parseInt(_m.length);
			_len -= Math.floor(_m2.length*.75);
			if(_len < 5) _len = 5;
			var _width = _len*8;
			if(locale == "ar_ae") _width = _len*5;
			$t.css({minWidth:(_width)+'px'});
			if(isIE6) $t.css({width:(_len*8)+'px'});
			if(isIE6 && (locale == "ar_ae")) $t.css({width:(_len*5)+'px'});
		});
		//update icons in Panel
		updateWBox();
	});
	
	// Module Tab effect
	$("div.Module ul.TabEffect").each(function(){
		var $ul = $(this), $tabs = $ul.find("a.Tab");
		$tabs.click(function(){
			$ul.find('li').removeClass('Active');
			$(this).parent().addClass('Active');
			return false;
		});
	});
	
	//fix Nav boxes height for wrapped text
	$("div.NavBox > a span").each(function(){
		var $t = $(this), _h = $t.height();
		if(_h > 20) {
			$t.css({padding:'15px 70px 8px 11px'});
		}
		if(_h > 20 && locale=="ar_ae"){
			$t.css({padding:'15px 11px 8px 30px'});
		}
		
	});
	$("ul.SubNav").prev("a").css({paddingBottom:'15px'});

	
	//Carousel functionality
	$("div.Carousel1").each(function(){
		var $me = $(this), $car = $me.find(".Car");
		//handles Carousel1 menu hover
		$me.find("ul.Menu li").hover(
			function(){
				var $t = $(this);
				$t.addClass('Hover');
			},
			function(){
				$(this).removeClass('Hover');
			}
		).filter(":first").addClass('First').end()
		.filter(":last").addClass('Last').end()
		// assign click handler to menu
		.find("> a").bind('click',function(){
			//set this parent selected
			var $a = $(this), ndx = $me.find(".Menu li a").index($a);
			moveCar(ndx+1,function(){
				$a.parent().siblings("li").removeClass('Selected')
				.end().addClass('Selected');
				});
			return false;
		});
		
		var carW = $car.find(">li:first").width();
		var iniCarWidth = function(){
			var carLen = $car.find(">li").length;
			$car.width(carW * carLen);
		}
		iniCarWidth();
		
		var moveCar = function(iPos,fn){
			var curPos = (iPos * carW)*-1;
			var anim = {left:curPos+'px'};
			if(locale == "ar_ae") anim = {right:curPos+'px'};
			$car.animate(anim,400,function(){
				if(fn) fn();
			});
		}
		
		//fix for H2
		$me.find(".Car li h2").each(function(){
			var $t = $(this);
			if($t.height() > 40){
				$t.css({bottom:12});
			}
		});
		
	});
	
	//Tabs1 functionality
	$("div.Tabs1").each(function(){
		var $me = $(this), $wrap = $me.find(".PaneWrapper"), $panes = $wrap.find(".Pane");
		var $ul = $("<ul class='Tabs' />");
		
		//set default tab
		if(!$wrap.find(".PaneDefault").length) $panes.eq(0).addClass("PaneDefault");
		
		//generate tabs
		$panes.each(function(){
			var $t = $(this), _text = $t.find("h3").text();
			var $li = $("<li><a href='#'>"+ _text +"</a></li>");
			if($t.hasClass('PaneDefault')) $li.addClass('Active');
			$li.appendTo($ul);
		});
		$ul.prependTo($me);
		
		//tabs click handler
		$ul.find("li a").bind('click',function(){
			var $t = $(this), ndx = $ul.find("li a").index($t);
			$(this).parent().addClass('Active').siblings().removeClass('Active');
			$panes.removeClass('PaneDefault').eq(ndx).addClass('PaneDefault');
			return false;
		});
		
	});
	setTimeout(function(){
		$("div.Tabs1 li.Active a").click();
	},200);
	
	//Table1 classname helper
	$("div.Table1").each(function(){
		var $me = $(this);
		$me.find('tr:last').find('td').addClass('last-row');
		$me.find('tr').find('td:first,th:first').addClass('first-col');
		$me.find('tr').find('td:last,th:last').addClass('last-col');
		//handles table with group tab
		$me.find('tr.table-tabs th').each(function(){
			$(this).removeClass('first-col');
			$(this).removeClass('last-col');
		});
		if($me.find('tr.table-tabs').length && $me.find('tr.table-tabs th:last').hasClass('right-tab')){
			$me.find('tr.table-tabs').next('tr').find('th:last').css({backgroundPosition:'50% 0'});
		}
	});
	
	//FAQs functionality
	$("div.FAQs").each(function(){
		var $me = $(this), $li = $me.find(".FAQList li");
		var $index = $("<ul class='Index' />");
		
		//create index and assign anchor names
		$li.each(function(i){
			var $t = $(this), _txt = $t.find('a.Question').text();
			$("<li><a href='#Question"+ i +"'>"+ _txt +"</a></li>").appendTo($index);
			
			$("<a name='Question"+i+"'></a>").insertBefore($t.find('a.Question'));
		});
		$index.insertBefore($me.find('.FAQList'));

	});
	
	//Side navigation Fix
	$("ul.SubNav2 li.Selected, ul.SubNav li.Selected").each(function(){
		if(!$(this).find("ul").length) $(this).addClass('NoChild');
	});
	
	
	$("ul.ImageGallery li a").click(function(){
		var $t = $(this), _mediaPath = $t.attr('href');
		if(_mediaPath.match(/\.flv/)) showOverlay2($t);
		else showOverlay($t);
		return false;	
	});
	//$(".CurveCorner").corner({});
	
	var showOverlay = function($a){
		var $page = $("body"), _pageH = $page.height();
		var $ovr = $("<div class='OverlayMask' />").height(_pageH).css({opacity:.8}).appendTo($page);
		var $img = $("<img src='"+$a.attr('href')+"' />").css({display:'none'});
		var _caption = $a.find('img').attr('alt');
		var $caption = $("<span class='Caption'>"+_caption+"</span>");
		var $close = $("<span class='Close'>X</span>");
		$img.appendTo($page);
		$img.load(function(){
			var _W = $img.width(), _H = $img.height();
			var $canvas = $("<div class='Overlay' />").width(_W+80).height(_H+30).css({marginLeft:((_W+80)/2)*-1,marginTop:((_H+30)/2)*-1});
			var $curve = $("<div class='CurveCorner' />");
			var _curveS = {
				tl: { radius: 10 },
				tr: { radius: 10 },
				bl: { radius: 10 },
				br: { radius: 10 },
				antiAlias: true,
				autoPad: true,
				validTags: ["div"]
			};
			if(isIE6){
				$page.find("select").css({display:'none'});
			}
			$canvas.appendTo($page);
			$curve.appendTo($canvas);
			if(!isIE6) {
				$curve.corner(_curveS);
				$img.appendTo($curve).css({padding:'0 40px 40px',display:'block'});
			}else $img.appendTo($curve).css({padding:'30px 40px 40px',display:'block'});
			
			$caption.insertAfter($img);
			$close.insertAfter($img);
		});
		
		$ovr.click(function(){
			closeOverlay();
		});
		$close.click(function(){
			$ovr.click();
		});
	}
	var showOverlay2 = function($a){
		var $page = $("body"), _pageH = $page.height();
		var $ovr = $("<div class='OverlayMask' />").height(_pageH).css({opacity:.8}).appendTo($page);
		var _videoPath = $a.attr('href');
		var _caption = $a.find('img').attr('alt');
		var $caption = $("<span class='Caption'>"+_caption+"</span>");
		var $close = $("<span class='Close'>X</span>");
		var $canvas = $("<div class='Overlay' />").width(600).height(385).css({marginLeft:(600/2)*-1,marginTop:(385/2)*-1});
		var $curve = $("<div class='CurveCorner' />");
		var $flash = $("<div class='WrapVideo' />").css({width:'auto',margin:'0 10px',height:385}).append("<div id='VideoPlayer' />");
		var _curveS = {
				tl: { radius: 10 },
				tr: { radius: 10 },
				bl: { radius: 10 },
				br: { radius: 10 },
				antiAlias: true,
				autoPad: true,
				validTags: ["div"]
			};
		
		$canvas.appendTo($page);
		$curve.appendTo($canvas);
		$flash.appendTo($curve);
		if(!(isIE6 || isIE7)) {
			$curve.corner(_curveS);
			$caption.css({bottom:'10px'});
		}
		
		$caption.insertAfter($flash);
		$close.insertAfter($flash);
		if(isIE6){
			$page.find("select").css({display:'none'});
		}
		var flashvars = {fileName:_videoPath,color1:0x999999,allowFullScreen:true}, params = {wmode:'opaque',allowScriptAccess:'always',allowFullScreen:true}, attributes = {};
		swfobject.embedSWF("../$Common/Flash/VideoPlayer.swf?123", "VideoPlayer", "530", "322", "9.0.0","expressInstall.swf", flashvars, params, attributes);
		
		$ovr.click(function(){
			closeOverlay();
		});
		$close.click(function(){
			$ovr.click();
		});
	}
	
	var closeOverlay = function(){
		$(".Overlay,.OverlayMask").remove();
	}
	
	
	//Expandable1 handler
	$("ul.Expandable1").each(function(){
		//generate toggle buttons and assign click handler
		$(this).find(">li").append("<span class='Toggle' />")
		.find(".Toggle").click(function(){
			$(this).parent().siblings("li").removeClass('Expanded').end()
			.toggleClass('Expanded');
		});
	});
	
	
	// remove empty <p> tags
	$("#Body p").each(function(){
		var $t = $(this), _t = $t.text();
		if(_t.length < 2 && _t.match(/\u00a0/g)) $t.remove();
	});
	$("div.Copy div.PaneWrapper").find(">p").each(function(){
		var $t = $(this);
		$t.text($t.text().replace(/\u00a0/g,' '));
		if($t.text() == ' ') $t.remove();
	});
	if($("div.Copy div.PaneWrapper .Pane").length < 1) $("div.Copy div.PaneWrapper").remove();
	
	
	// Print and email utility links
	var _strPrint = locale == "ar_ae" ? "طبع" : "Print";
	var _strEmail = locale == "ar_ae" ? "البريد الإلكتروني" : "Email";
	$("#Body:has(ul.Breadcrumb)")
	.append("<ul id='Utility'><li class='Email'><a href='#'>"+_strEmail+"</a></li><li class='Print'><a href='#'>"+_strPrint+"</a></li></ul>");
	$("#Utility li a").click(function(){
		var $t = $(this);
		if($t.parent().hasClass('Print')) {
			window.print();
			return false;
		}
		if($t.parent().hasClass('Email')) {
			var _subject = "I thought this might interest you...";
			var _body = window.location.href;
			$t.attr('href','mailto:'+'&subject='+_subject+'&body='+_body)
			return true;
		}
	});
	
	//Fix NewsList
	$("ul.NewsList li").each(function(){
		var $t = $(this);
		if(!$t.find("img.Thumb").length) $t.addClass('NoImage');
	});
	
	// Fix flexible height footer sitemap
	$("#FooterSitemap").each(function(){
		var _h = $(this).height()+30;
		$("#Footer").css({minHeight:_h});
	});
	
});

//:: GLOBAL functions

// email validation
var isEmail = function(sEmail){
	return sEmail.match(/(^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$)/gi);
}

//global cookie functions
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}