/**
* Copyright (c) 2007, Impact Proximity
* All rights reserved.
* @author Jerome Conde <j.conde@impactbbdo.ae>
* @version 1.0.1
*/

$(function(){
	/** global vars */
	var locale = "en_gb";
	if(window.location.href.indexOf("ar_ae") > -1)
		locale = "ar_ae";
	
	/** Add 'FirstChild' class for ie6 */
	var firstChild = function(){
		$("li:first-child").addClass("FirstChild");
	}
	if($.browser.msie && $.browser.version == "6.0") firstChild();
	
	/**
	 *
	 */
	var autoText = "";
	$("div.Header input.Textbox")
	.bind('focus',function(){
		autoText = $(this).val();
		$(this).val("");
	})
	.bind('blur',function(){
		if($(this).val() == "")
		$(this).val(autoText);
	})
	;
	
	/**
	 * Accordion handler
	 */
	$("ul.Accordion li h3")
	.bind('click',function(){
		if($(this).parent().hasClass("Expanded")) return;
		var $exp = $("ul.Accordion li.Expanded div");
		$exp.slideUp(200,function(){
			$(this).parent().removeClass("Expanded");
		});
		$(this).parent()
		.find("div").slideDown(200,function(){
			$(this).parent().addClass("Expanded");
		})
		;
	})
	;
	
	/**
	 * Module tab handler
	 */
	$("div.ModulePanel .Tabs li > a")
	.bind('click',function(){
		var $active = $("div.ModulePanel .Tabs li.Selected");
		var $curr = $(this).parent();
		if($curr.hasClass("Selected")) return false;
		$active.find("img")
		.animate({marginTop:37},100,function(){
			$active.removeClass("Selected");
			$(this).animate({marginTop:0},200);
			$curr.find("img").animate({marginTop:37},100,function(){
				$curr.addClass("Selected");
				$curr.find("div").css({opacity:0})
				.animate({opacity:1},400);
				$(this).animate({marginTop:0},200);
			});
		});
		return false;
	})
	;
	
	/**
	 * Assign number class names
	 * for Seven things section
	 */
	$("div.SevenThings td")
	.each(function(){
		$(this).addClass("Num"+($("div.SevenThings td").index(this)+1));
	})
	;
	
	/**
	* Team management section
	*/
	$("div.ExecList .Module2")
	.bind('click',function(){
		$("div.ExecList .Module2").addClass("Module2Collapse");
		$(this).removeClass("Module2Collapse");
		
		$("div.ExecList .Module2 > em").each(function(){
			var txt = $(this).html();
			$(this).html(txt.replace(/(\<BR\s*\/*\>)|(\<br\s*\/*\>)/g,", "));
		});
		var txt = $(this).find("> em").text();
		$(this).find("> em").html(txt.replace(",","<br />"));
	})
	;
	$("div.ExecList > div.Col1").find(".Module2:first")
	.css({marginTop:0})
	;
	$("div.ExecList .Module2:eq(0)").trigger("click");
	
	//adjust h3 top margin if there is no profile image
	$("div.ExecList .Module2 h3").each(function(){
		if(!$(this).parent().find("img").length){
			$(this).css({width:280,marginTop:0});
		}
	});
	
	
	/**
	* print handler
	*/
	$("a.Print").bind("click",
		function(){
			window.print();
			return false;
		}
	);
	
			/**
			* @desc Ticker for the homepage
			*/
			
			var urlPrefix = "/MediaCenter/NewsDetail_en_gb.asp?";
			if(locale == "ar_ae") urlPrefix = "/MediaCenter/NewsDetail_ar_ae.asp?";
			var xhrURL = "http://www.alkhaliji.com/NewsFeed/Ticker_en_gb.aspx";
			if(locale == "ar_ae") xhrURL = "http://www.alkhaliji.com/NewsFeed/Ticker_ar_ae.aspx";
			
			var tickerTxt = ["Loading headlines..."];
			var arrLinks = ["#"];
			var $tickTxt = $("#TickTxt");
			var $tickCursor = $("#Cursor");
			
			/**
			* @desc simulate typing effect function
			* @param $holder - element which holds the type textnode
			* @param sTxt - string to simulate
			* @param nSpeed - speed in milliseconds
			* @param $cursor - element that represent as cursor
			*/
			var typeTimeout = null;
			var typeEffect = function($holder,sTxt,nSpeed,$cursor){
				var txtLen = sTxt.length;
				var currPos = 0;
				var tmpTxt = "";
				
				//set the width of anchor
				$tickTxt.parent().css({width:txtLen*6+'px'});
				//window.status = txtLen*6;
				var hideCursor = function(){
					$cursor.css({display:'none'});
				}
				var showCursor = function(){
					$cursor.css({display:'inline'});
				}
				
				var typeText = function(){
					tmpTxt += sTxt.charAt(currPos);
					$holder.text(tmpTxt);
					currPos += 1;
					if($cursor.is(":visible")) hideCursor();
						else showCursor();
					if(currPos >= txtLen) {
						hideCursor();
						clearTimeout(typeTimeout);
						return;
					}
					typeTimeout = setTimeout(typeText,nSpeed);
				}
				//start typing
				typeText();
			}
			
			/**
			* @desc shorten item text
			*/
			var shorten = function(sTxt,limit){
				if(sTxt.length < limit) return sTxt;
				var val = "";
				val = sTxt.substring(0,limit).split(" ");
				val[val.length-1] = "...";
				return val.join(" ");
			}
			
			/**
			* @desc setup rotator for news items
			*/
			var itemIndex = 0;
			var rotateTimeout = null;
			var typeSpeed = 10;
			var rotateInterval = 4000;
			var textMaxWidth = 55;
			//change this variable with the final one later.
			var arrFeed = tickerTxt;
			var newsRotator = function(aNews,interval){
				if(itemIndex == aNews.length) itemIndex = 0;
				$tickTxt.parent().attr("href",arrLinks[itemIndex]);
				typeEffect($tickTxt,shorten(aNews[itemIndex],textMaxWidth),typeSpeed,$tickCursor);
				itemIndex++;
				var x = function(){newsRotator(aNews,interval)};
				//recursion call to news rotator
				rotateTimeout = setTimeout(x,interval);
			}
			
			//start news rotator
			if($(".Ticker").length){
				//ajax request
				$.get(xhrURL,function(data){
					var $data = $(data).find("ul li");
					$data.each(function(i){
						tickerTxt[i] = $(this).find("a").text();
						tickerTxt[i] = tickerTxt[i].replace(/\"/g,"&quot;");
						arrLinks[i] = urlPrefix + $(this).find("a").attr('href').split("?")[1];
					});
					
					//if(ticker.installedVer.rev > 0){
					if(ticker.installedVer.rev > 0){
						ticker.addVariable("headings",tickerTxt.join(","));
						ticker.addVariable("URLs",arrLinks.join(","));
						$("#Ticker").css({padding:0,height:'40px'});
						ticker.write("Ticker");
					}
					else{
						newsRotator(arrFeed,rotateInterval);
					}
				});
			}
			
			
			/**
			* @desc assign event handlers to the ticker
			*/
			
			$tickTxt
			.bind('mouseover',function(){
				clearTimeout(rotateTimeout);
				var currText = arrFeed[itemIndex-1];
				if(currText.length > textMaxWidth){
					$tickTxt.parent().css({width:currText.length*6+'px'});
					var diffW = $(this).parent().width() - $(this).width();
					$tickTxt.text(currText);
					if(locale == "en_gb"){
						$(this).parent().animate({left:diffW*-1},3000,function(){
							$(this).animate({left:0},2000);
						});
					}
					else{
						$(this).parent().animate({right:diffW*-1},3000,function(){
							$(this).animate({right:0},2000);
						});
					}
				}
			})
			.bind('mouseout',function(){
				$(this).text(shorten($(this).text(),textMaxWidth));
				if(locale == "en_gb"){
					$(this).parent().stop().css({left:0});
				}
				else{
					$(this).parent().stop().css({right:0});
				}
				clearTimeout(rotateTimeout);
				var x = function(){newsRotator(arrFeed,rotateInterval)};
				rotateTimeout = setTimeout(x,2000);
			})
			;
			
			/**
			* @desc Previous and Next buttons
			*/
			$(".TickerWrap .Control span")
			.bind('click',function(){
				if($(this).hasClass('Prev')){
					itemIndex--;
					itemIndex--;
					if(itemIndex < 0) itemIndex = arrFeed.length-1;
				}
				if($(this).hasClass('Next')){
					if(itemIndex > arrFeed.length-1) itemIndex = 0;
				}
				clearTimeout(rotateTimeout);
				var x = function(){newsRotator(arrFeed,rotateInterval)};
				rotateTimeout = setTimeout(x,100);
			})
			;
			
	/**
	* Reuters article details
	*/
	if($(".ReutersFeed").length){
		var storyID = window.location.href.split("?")[1];
		var $theHeading = $(".Article h3:first");
		var $theDateline = $(".Article .Dateline");
		var $theCopy = $(".ArticleCopy");
		if(storyID){
			var ajaxURL = "http://www.alkhaliji.com/NewsFeed/NewsDetail_en_gb.aspx?" + storyID;
			if(locale == "ar_ae") ajaxURL = "http://www.alkhaliji.com/NewsFeed/NewsDetail_ar_ae.aspx?" + storyID;
			$.get(ajaxURL,function(data){
				var $data = $(data).find(".Article");
				var heading = $data.find("h3:first").html();
				var dateline = $data.find(".Dateline").html();
				var copy = $data.find(".ArticleCopy").html();
				
				//render news details
				$theHeading.html(heading);
				$theDateline.html(dateline);
				$theCopy.html(copy);
				$("#divImage").css({padding:'10px',paddingLeft:0,float:'left'});
				if(locale == "ar_ae") $("#divImage").css({padding:'10px',paddingRight:0,float:'right'});
			});
		}
		else{
			//window.location.href = ("http://localhost/");
		}
	}
	if($(".ReutersList").length){
		var decache = Math.floor(Math.random()*1000);
		$(".ReleaseList h3").css({padding:'15px 0 0'});
		var newslist = $("<ul class='List'></ul>").appendTo($(".ReleaseList"));
		var ajaxURL = "http://www.alkhaliji.com/NewsFeed/Ticker_en_gb.aspx?decache="+decache;
			if(locale == "ar_ae") ajaxURL = "http://www.alkhaliji.com/NewsFeed/Ticker_ar_ae.aspx?decache="+decache;
		var urlPrefix = "/MediaCenter/NewsDetail_en_gb.asp?";
			if(locale == "ar_ae") urlPrefix = "/MediaCenter/NewsDetail_ar_ae.asp?";
		$.get(ajaxURL,function(data){
			var news = $(data).find("ul:first");
			news.find("li a").each(function(){
				var storyid = $(this).attr("href").split("?")[1];
				if(storyid){
					$(this).attr("href",urlPrefix + storyid);
				}
			});
			$(".ReleaseList h3").remove();
			newslist.html(news.html());
		});
	}

});

function openOverlay(){
	var decache = Math.random();
//	var popup = new SWFObject("/Common/Flash/RamadanPopup.swf?"+decache, "inst_Popup", "650", "551", "8", "#FFFFFF");
//		popup.addParam("wmode", "transparent");
	$(".Page").css({position:'relative'});
	
	if($("#Popup").length) return;
	$("<div id='Popup' />")
	.css({width:800,height:537,position:'absolute',left:70,top:128})
	.appendTo(".Page")
	;
//	popup.write("Popup");
	
	/** Using image only **/
	$("#Popup")
	.css({border:'#000 solid 1px'})
	.append("<img src='/Common/Image/Content/popup.jpg' />")
	.append("<img class='Button' src='/Common/Image/Generic/CloseButton.gif' />")
		.find(".Button").css({position:'absolute',right:0,top:0,cursor:'pointer'})
		.bind('click',function(){closeOverlay();})
	;
}

function closeOverlay(){
	$("#Popup").remove();
}
function openOverlayAr(){
	var decache = Math.random();
	/*var popup = new SWFObject("/Common/Flash/RamadanPopup_ar_ae.swf?"+decache, "inst_Popup", "650", "551", "8", "#FFFFFF");
		popup.addParam("wmode", "transparent");
		//popup.write("Popup");
	$(".Page").css({position:'relative'});
	$("<div id='Popup' />")
	.css({width:650,height:551,position:'absolute',left:150,top:128})
	.appendTo(".Page")
	;
	popup.write("Popup");*/

	$(".Page").css({position:'relative'});
	
	if($("#Popup").length) return;
	$("<div id='Popup' />")
	.css({width:800,height:537,position:'absolute',left:70,top:128})
	.appendTo(".Page")
	;
//	popup.write("Popup");
	
	/** Using image only **/
	$("#Popup")
	.css({border:'#000 solid 1px'})
	.append("<img src='/Common/Image/Content/popuparabic.jpg?"+decache +"' />")
	.append("<img class='Button' src='/Common/Image/Generic/CloseButton.gif' />")
		.find(".Button").css({position:'absolute',right:0,top:0,cursor:'pointer'})
		.bind('click',function(){closeOverlay();})
	;
}
function closeOverlayAr(){
	$("#Popup").remove();
}