/**
* Default.js v11
* 20-09-2011 am - some other fixes
* 16-09-2011 am - added setGallerySliderCallbacks for main page gallery
* 23-11-2011 js - removed gallery image click default handler
* ...
*/

var applySliderGlobal1 = null;
var applySliderGlobal2 = null;
var applySliderGlobal3 = null;
var applySliderGlobal4 = null;

function divide ( numerator, denominator ) {
    var remainder = numerator % denominator;
    return quotient = ( numerator - remainder ) / denominator;   
}

$(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 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();
	}
	lastChild();
	
	//auto text handler
	$("div.Header input.Textbox,div.FAQSearch input.Textbox")
	.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);
		});
	});
	
	//external links
	$("a[rel=external],a[rel=External]").click(function(){
		$(this).attr('target','_blank');
	});
		
	/** sucker fish drop down */
	if($("ul.Nav1 > li.Selected").length) {
		var restX = $("ul.Nav1 > li.Selected").position().left + ($(this).find('a').width()+28)/2 + 2;
	}
	else var restX = 0;
	var $arrow = $("div.TopArrow").css({left:restX,zIndex:2});
	if($('ul.Nav1 > li.Selected').length){
		$arrow.css({display:'block'});
	}
	$("ul.Nav1 > li").hover(
	 	function(){
			//var $t = $(this), _x = $t.offset().left + $t.width() - $(".HeaderNav").offset().left;
			var $t = $(this), _x = $t.position().left + ($(this).find('a').width()+28)/2;
			$("ul.Nav1 > li.Selected ul").css({display:'none',zIndex:0});
			$("ul",this).css({display:'block',zIndex:1})
			$arrow.css({display:'block'}).css({left:_x});
		}, 
		function(){
			if(restX) $arrow.css({left:restX});
			else $arrow.css({display:'none'});
			$("ul",this).css({display:'none',zIndex:0});
			$("ul.Nav1 > li.Selected ul").css({display:'block',zIndex:1});
		}
	);
	
	
	// Floated box fix
	$('div.Box:even').each(function(i){
		
		var $t = $(this); $div = $('<div />').css({float:'right',width:640});
		if($t.parents('.SectionTwo').length || $t.is('.ForumHeight') ) return;
		if($t.parents('.healthPage').length) return;
		if($t.parents('.archivePage').length) return;
		if($t.parent().is('.ExpertList')) $div.css({width:620});
		$t.next('div.Box').andSelf().wrapAll($div);
		
	});
	
	// Image gallery
	var globalUpdateButtons = null;
	var globalSelectThumb = null;
	var globalStopRotate = null;

	$('div.PhotoSectionBottom').each(function(){
		var $me = $(this), $mask = $me.find('.PhotoSlider'), $left = $me.find('.SmallArrowLeft a'), $right = $me.find('.SmallArrowRight a');
		var $car = $me.find('.PhotoSlider ul'), $thumbs = $car.find('li a'), _count = $car.find('img').length, _w = 58, _n = 5, _m = 9, _speed = 600;
		
		// build big images
		var $em = $('<div />');
		var $mask = $('div.PhotoSectionTop .ImageWrapper div.Mask');
		var spanElements = 0;
		document.getElementById('loading').style.display = 'none';
		
		$thumbs.each(function(){
			var $t = $(this);
			if($t.parent().is(':first-child')) $t.parent().addClass('Selected');
			$em.append('<span id="spanImage_'+spanElements+'"><img id="imgBigImage_'+spanElements+'" src="'+$t.attr('href')+'" /></span>');
			
			$t.click(function(event){
        event.preventDefault();
				$thumbs.parent().removeClass('Selected');
				$t.parent().addClass('Selected');
				var _n = $thumbs.index(this);
				$mask.find('div').css({left: _n*400*-1});
				globalStopRotate();
				globalUpdateButtons();
				return false;
			});
			spanElements++;
		});
		if (js_secondaryChannel!='' && js_secondaryChannel!='gallery' && js_secondaryChannel!='photos'){
			$em.append('<span id="spanImage_MPU"><iframe id="mpuframeBig" src="'+mpuUrlFinal+'" scrolling="no" frameborder="0" style="margin-right: 40px; background-color: #191919; display: inline; min-height:250px; width: 300px; border: none; overflow: hidden; z-index: 1000; margin-top:60px;" allowtransparency="true"></iframe></span>');
		}
		
		$em.appendTo($mask);
		if (js_secondaryChannel!='' && js_secondaryChannel!='gallery' && js_secondaryChannel!='photos'){
			$mask.find('span#spanImage_'+(spanElements-1)).css('display','none');
		}
		
		setTimeout(function(){
			$mask.find('span img').each(function(){
				if($(this).width() > $(this).height()) $(this).parent().addClass('Landscape');
			});
		},500);
		
		// adjust width of car
		$car.width(_count*_w);
		
		function getPos(){ return parseInt($car.css('left'));}
		function updateButtons(){
			var _x = getPos();
			$left.removeClass('Disabled').find('img').css({opacity:1});
			$right.removeClass('Disabled').find('img').css({opacity:1});
			if(_x >= 0) $left.addClass('Disabled').find('img').css({opacity:.3});
			if(_x <= (_count-_m)*_w*-1) $right.addClass('Disabled').find('img').css({opacity:.3});
		}
		updateButtons();
		
		$left.click(function(){
			
			var $t = $(this);
			if($t.is('.Disabled') || $car.is(':animated')) return false;
			$car.animate({left:'+='+_w*_n+'px'},_speed,function(){
				updateButtons();
			});
			return false;
		});
		
		$right.click(function(){
			var $t = $(this);
			if($t.is('.Disabled') || $car.is(':animated')) return false;
			$car.animate({left:'-='+_w*_n+'px'},_speed,function(){
				updateButtons();
			});
			return false;
		});
		
		var selectThumb = function(n){
			var _pos0 = $car.parent().offset().left;
			var _pos1 = $car.parent().offset().left + $car.parent().width();
			var _pos2 = $thumbs.eq(n).parent().offset().left;
			$thumbs.parent().removeClass('Selected').end().eq(n).parent().addClass('Selected');
			if(_pos1 <= _pos2) $right.click();
			if(_pos0 >= _pos2) $left.click();
		}
		globalSelectThumb = selectThumb;

	});
		
	$('div.PhotoSectionTop').each(function(){
		var $me = $(this), $mask = $me.find('.Mask'), $left = $me.find('.DivArrowLeft a'), $right = $me.find('.DivArrowRight a');
		var $car = $me.find('.Mask div'), _count = $car.find('img').length, _w = 400, _n = 1, _speed = 800;
		var _timeout = null, $playBtn = $me.find('.PlayButton a');
		var playSpeed = function(){
			var $a = $me.find('.MotionUL li a'), n = $a.index($me.find('.MotionUL li a.Selected'));
			if(n < 0) n = 1;
			return [5000,2500,1000][n];
		}
		
		var rotateImage = function(){
			_timeout = setTimeout(function(){
				if($right.is('.Disabled')){
					$car.animate({left:0},200,function(){
						updateButtons();
						rotateImage();
					});
				}
				else{
					$right.click();
					rotateImage();
				}
				if (js_secondaryChannel!='' && js_secondaryChannel!='gallery' && js_secondaryChannel!='photos'){
					if($right.is('.Disabled')){
						reloadIFrame(0);
					}
				}
			},playSpeed());
			var _img = $playBtn.find('img').attr('src');
			_img = _img.replace('Button.gif','ButtonPause.gif');
			$playBtn.addClass('Playing').find('img').attr('src',_img);
		}
		var stopRotate = function(){
			var _img = $playBtn.find('img').attr('src');
			_img = _img.replace('Pause.gif','.gif');
			$playBtn.find('img').attr('src',_img);
			clearTimeout(_timeout);
			$playBtn.removeClass('Playing');
		}
		globalStopRotate = stopRotate;
		
		$playBtn.click(function(){
			if($(this).is('.Playing')) stopRotate();
			else rotateImage();
			return false;
		});
		
		// adjust width of car
		$car.width(_count*_w);
		
		function getPos(){ return parseInt($car.css('left'));}
		function updateButtons(){
			var _x = getPos();
			$left.removeClass('Disabled').find('img').css({opacity:1});
			$right.removeClass('Disabled').find('img').css({opacity:1});
			if(_x >= 0) $left.addClass('Disabled').find('img').css({opacity:.3});
			if(_x <= (_count-_n)*_w*-1) $right.addClass('Disabled').find('img').css({opacity:.3});
			
			globalSelectThumb(_x*-1/_w);
		}
		updateButtons();
		globalUpdateButtons = updateButtons;
		
		$left.click(function(){
			stopRotate();
			var $t = $(this);
			if($t.is('.Disabled') || $car.is(':animated')) return false;
			$car.animate({left:'+='+_w+'px'},_speed,function(){
				updateButtons();
			});
			return false;
		});
		
		$right.click(function(){
			stopRotate();
			var $t = $(this);
			if($t.is('.Disabled') || $car.is(':animated')) return false;
			$car.animate({left:'-='+_w+'px'},_speed,function(){
				updateButtons();
			});
			return false;
		});
	});
	
	$('div.SlowSlider').each(function(){
		var $me = $(this), $a = $me.find('.MotionUL a'), $span = $me.find('> span');
		$a.each(function(i){
			var pos = [25,85,145][i];
			$(this).click(function(){
				$a.filter('.Selected').removeClass('Selected');
				$(this).addClass('Selected');
				$span.animate({left:pos},200);
				return false;
			});
		})
	});
	
	//homepage video gallery
	$("div.VideoGallery").each(function(){
		var $me = $(this), $thumbs = $me.find(".ThumbnailSmall td > a"), $li = $me.find('ul.Thumbnails > li');
		var $bigWrap = $('<div class="ThumbnailBig" />'), $h3 = $('<h3 />'), $desc = $('<p />');
		var setH3Desc = function($LI){
			$h3.text($LI.find('td:eq(1) strong').text());
			$desc.text($LI.find('td:eq(1) span').text());
		}
		// render big thumbnails
		$li.each(function(i){
			$(this).find('img.BigThumbnail').clone().appendTo($bigWrap);
			if(i == 0) setH3Desc($(this));
		});
		$bigWrap.insertAfter($me.find('h2'));
		$h3.insertAfter($me.find('h2'));
		$desc.appendTo($me);
		
		var $big = $me.find(".ThumbnailBig img");
		$thumbs.eq(0).addClass('Selected');
		$thumbs.click(function(){
			var n = $thumbs.index(this);
			$big.hide();
			$big.eq(n).css({display:'inline',opacity:0}).animate({opacity:1},800);
			setH3Desc($(this).parents('li'));
			$thumbs.removeClass('Selected').filter(this).addClass('Selected');
			return false;
		});
		var $vid = "";
		
		if (js_primaryChannel=='Home' && js_secondaryChannel==''){
			$vid = $("div.VidPlayer").css({left:-320,top:'0%'});
		}else{
			$vid = $("div.VidPlayer").css({left:-330,top:'0%'});
		}
		var $lucent = $vid.find(".Translucent").css({opacity:.9});
		var $close = $vid.find("span.Close");
		var $player = $vid.find('div.Player');
		//Added for next image enhancement
        var $nextImgAnchor = $vid.find('a.nextImg'); 
		//End Added for next image enhancement
		var playVideo = function(videoURL){
			//if(vidPlayerPath == 'undefined') return;
			var playerid='';
			var videoid='';
			if(videoURL!=""){
			var splitvar=videoURL.split('@');
			 playerid=splitvar[0];
			 videoid=splitvar[1];
			}
			var movielnk='http://c.brightcove.com/services/viewer/federated_f9/'+playerid+'?isVid=1';
			var flashvars = {
				videoId:videoid,
				playerID:playerid,
				domain:'embed',
				dynamicStreaming:true
			};
			var params = {
				movie:movielnk,
				bgcolor:'#FFFFFF',
				allowScriptAccess:'always',
				base:'http://admin.brightcove.com',
				seamlesstabbing:false, 
				allowFullScreen:true, 
				swLiveConnect:true
			};
			var attributes = {
				id:'flashObj',
				width:'582',
				height:'376',
				codebase:'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,47,0'
			};
			swfobject.embedSWF(movielnk, "VideoHolder", "582", "376", "9.0.0","expressInstall.swf", flashvars, params, attributes);
		}
		var vidOverlay = function(n){
			if(!$vid.is(':visible')) $vid.fadeIn(200);
			// put info
			var $info = $vid.find('.VideoInfo'), $H3 = $info.find('h3'), $P = $info.find('p'), $anchorTag = $info.find('a'), $table;
					   //Enhnacement for adding URL to <h3> tag
			var detailPageUrl;
			var urlString = $li.eq(n).find('td:(0) a').attr('href');
			if(urlString!=""){
							var urlArray=urlString.split('@');
							detailPageUrl=urlArray[2];                                                         
							$anchorTag.attr("href", detailPageUrl)
			}
			$H3.text($li.eq(n).find('td:eq(1) strong').text());
			$P.html($li.eq(n).find('p.LongDesc').html());
			// remove existing & add the next thumbnail
			$vid.find('table').remove();
			var x = n + 1;
			//if(x >= $li.length) x = 0;
			//Remove next image link
			if((x+1) >= $li.length){
				$nextImgAnchor.hide();
			}

			$table = $li.eq(x).find('table').clone();
			$table.insertBefore($vid.find('a.More'));
			// add click handler to thumbnail
			$table.find('td:eq(0) a').click(function(){
				vidOverlay(x);
				//Added for next image enhancement
				incrementValue =incrementValue+1;
				//End Added for next image enhancement	
				return false;
			});
			
			// play video
			var videoURL = $li.eq(n).find('td:(0) a').attr('href');
			var playerid='';
			var videoid='';
			if(videoURL!=""){
			var splitvar=videoURL.split('@');
			 playerid=splitvar[0];
			 videoid=splitvar[1];
			}
			//flvPath = flvPath.split('?')[1];
			//$player.empty().append('<div id="VideoHolder" />');
			//playVideo(videoURL);
			
			$player.empty().append('<iframe id="contentFRAMEleft" frameborder="0" width="582" height="376" scrolling="no" align="left" src="/vgn-ext-templating-anazahra/overrides/jsp/anazahra_VideoLoading.jsp?playerId='+playerid+'&videoId='+videoid+'"></iframe>');
		}
		//Added for next image enhancement
		var incrementValue = 1;
		var currentLiIndex ;
		$nextImgAnchor.click(function(){
	        var $table;	
	        var nextImg = currentLiIndex+incrementValue;
			//Remove next image link
            if((nextImg+1)>=$li.length){				
                $nextImgAnchor.hide();
			}

	        if(nextImg >= $li.length ){
			$vid.find('table').remove();
			   return false;
	        }		
			$vid.find('table').remove();
			$table = $li.eq(nextImg).find('table').clone();
			$table.insertBefore($vid.find('a.More'));
            incrementValue = incrementValue+1;	
			$table.find('td:eq(0) a').click(function(){				
				vidOverlay(nextImg);
				incrementValue =incrementValue+1;
				return false;
			});

		});		
		//End Added for next image enhancement	

		$big.click(function(){
			var n = $big.index(this);

			//Added for next image enhancement
			currentLiIndex = n+1 ;
			incrementValue = 1;
			//Remove next image link
			$nextImgAnchor.show();
			//End Added for next image enhancement	

			vidOverlay(n);
		});
		$close.empty().click(function(){
			$player.empty();
			$vid.fadeOut(400,function(){
				// clean up
			});
		});
		
	});
	
	//Poll box
	$(".VoteWrap a.SendArrow").click(function(){
		if($(".VoteWrap input:checked").length) {
			$(".VoteWrap").hide(200,function(){
				$(".ResultWrap").show();
			});
		}
		else alert('You need to choose first.');
		return false;
	});
	
	$(".ResultWrap a.SendArrow").click(function(){
		$(".ResultWrap").hide(200,function(){
			$(".VoteWrap").show();
		});
		return false;
	});
	
	// Quiz slider
	$('div.QuizGallery').each(function(){
		var $q = $(this), $slide = $q.find('div.SlideList');
		$slide.each(function(){
			var $me = $(this), $mask = $me.find('.SlideShow'), $left = $me.find('.Next a'), $right = $me.find('.Previous a');
			var $car = $mask.find('ul'), $thumbs = $car.find('li a:first-child'), _count = $car.find('li img').length, _w = 125, _n = 4, _m = 4 /*(total thumbs)*/, _speed = 600;
			
			// adjust width of car
			$car.width(_count*_w);
			
			// create indicator
			var _dots = Math.ceil($thumbs.length/_m);
			var $led = $('<ul class="Indicator" />');
			for(x=0;x<_dots;x++){$led.append('<li />')}
			$led.insertBefore($me).find('li:first').addClass('Active');
			
			function updateDots(){
				var n = getPos()*-1/_w/_m;
				$led.find('li').removeClass('Active').eq(n).addClass('Active');
			}
			$led.find('li').each(function(i){
				$(this).click(function(){
					$car.animate({left:_w*_n*i*-1+'px'},_speed,function(){
						updateButtons();
					});
				});
			});
			
			function getPos(){ return parseInt($car.css('left'));}
			function updateButtons(){
				var _x = getPos();
				$left.removeClass('Disabled').find('img').css({opacity:1});
				$right.removeClass('Disabled').find('img').css({opacity:1});
				if(_x >= 0) $left.addClass('Disabled').find('img').css({opacity:.3});
				if(_x <= (_count-_m)*_w*-1) $right.addClass('Disabled').find('img').css({opacity:.3});
				updateDots();
			}
			updateButtons();
			
			$left.click(function(){
				var $t = $(this);
				if($t.is('.Disabled') || $car.is(':animated')) return false;
				$car.animate({left:'+='+_w*_n+'px'},_speed,function(){
					updateButtons();
				});
				return false;
			});
			
			$right.click(function(){
				var $t = $(this);
				if($t.is('.Disabled') || $car.is(':animated')) return false;
				$car.animate({left:'-='+_w*_n+'px'},_speed,function(){
					updateButtons();
				});
				return false;
			});
			
		});
		
	});
	
	

	// Popular List box
                $('ul.PopularList').each(function(){
                                var $ul = $(this), $li = $ul.find('li'), $listPanel = $ul.nextAll('.List1');              
                                var getSel = function(){
									// updated to fix most popular issue on celebrity issue
                                                var mylist=document.getElementById("PopularList");
                                                var x=0;
                                                for (i=0; i < mylist.childNodes.length; i++){
                                                                if (mylist.childNodes[i].nodeName=="LI"){
                                                                                x++;                                       
                                                                                  if(mylist.childNodes[i].className == "Selected" || mylist.childNodes[i].className == "Selected LastChild"  || mylist.childNodes[i].className == "FirstChild Selected"){                                                              
                                                                                                                return x-1;
                                                                                  }
                                                                }
                                                }                                              
                                                return 2;
                                }
                                
                                $listPanel.css({display:'none'}).eq(getSel()).slideDown(300);
                                $li.find('a').click(function(){
                                                if($(this).parent().is('.Selected')) return false;
                                                $li.removeClass('Selected');
                                                $(this).parent().addClass('Selected');                                               
                                                $listPanel.slideUp(200).eq(getSel()).slideDown(300);
                                                return false;
                                });
                });

	
	// Style board tabs
	$('div.StyleBoardWrapper').each(function(){
		var $me = $(this), $tabs1 = $me.find('ul.TabsLevel1'), $li = $tabs1.find('li');
		var getSel = function(){return $li.index($('li.Selected',$tabs1))}
		var $panel1 = $tabs1.nextAll('.PanelLevel1');
		
		$panel1.css({display:'none'}).eq(getSel()).slideDown();
		
		$li.find('a').click(function(){
			if($(this).parent().is('.Selected')) return false;
			$li.removeClass('Selected');
			$(this).parent().addClass('Selected');
			$panel1.css({display:'none'}).eq(getSel()).slideDown();
			return false;
		});
		
	});
	$('div.StyleBoardWrapper').each(function(){
		var $me = $(this), $tabs2 = $me.find('ul.TabsLevel2'), $li = $tabs2.find('li');
		var getSel = function(){return $li.index($('li.Selected',$tabs2))}
		var $panel1 = $tabs2.nextAll('.PanelLevel2');
		
		$panel1.css({display:'none'}).eq(getSel()).slideDown();
		
		$li.find('a').click(function(){
			if($(this).parent().is('.Selected')) return false;
			$li.removeClass('Selected');
			$(this).parent().addClass('Selected');
			$panel1.css({display:'none'}).eq(getSel()).slideDown();
			return false;
		});
		
	});

	// START: style board handler
	if(typeof $('body').draggable != 'undefined'){
		$('ul.Grid li').wrapInner('<div />')
		.hover(function(){$(this).css({borderColor:'#ddd'})},function(){$(this).css({borderColor:'#fff'})})
		.draggable({
			revert:true,
			scroll:false,
			containment:$('div.ContentWrapper'),
			helper:'clone'
		});
	}
	var $canvas = $('div.Canvas'), $btnDelete = $('#delete'), $btnClone = $('#clone'), $btnForward = $('#forward'), $btnClearAll = $('#clearall');
	if(typeof $('body').droppable != 'undefined'){
		$canvas.droppable({
			activeClass: 'ui-state-hover',
			accept:'li.ui-draggable',
			tolerance:'intersect',
			drop:function(e,ui){
				var $dragged = $('.ui-draggable-dragging');
				var _left = itemOffset($dragged).left, _top = itemOffset($dragged).top;
				var $thumb = $dragged.css({display:'none'}).find('img');
				var _imgUrl = $thumb.attr('src').replace('small','large');
				var $newImg = $('<img src="'+ _imgUrl +'" />').css({width:160,minHeight:225,padding:9,left:_left,top:_top,cursor:'move'});
				$newImg.ready(function(){
					makeInteractive($newImg);
				});
				//makeInteractive($newImg);
			},
			over:function(){
			},
			out:function(){
			}
		});
	}

	// offset relative to canvas
	var itemOffset = function($item){
		var _pos = $item.offset();
		var _pos2 = $canvas.offset(), _left = _pos.left - _pos2.left, _top = _pos.top - _pos2.top;
		_left = _left > 350 ? 350 : _left; _left = _left < 0 ? 0 : _left;
		_top = _top > 228 ? 228 : _top; _top = _top < 0 ? 0 : _top;
		return {left:_left, top:_top};
	}
	
	var makeInteractive = function($img){
		var _optRes = {minWidth:50,maxWidth:500,maxHeight:450,aspectRatio:true,handles:'n, e, s, w, ne, se, sw, nw'};
		var _optDrag = {containment:$canvas};
		$img.appendTo($canvas).resizable(_optRes).parent().draggable(_optDrag);
		setSelected($img.parent());
		return $img.parent();
	}
	
	// actions
	var setSelected = function($sel){
		unSelectAll();
		$sel.addClass('ui-selected').find('.ui-resizable-handle',$canvas).css({display:'block'});
	}
	var unSelectAll = function(){
		$canvas.find('.ui-selected').removeClass('ui-selected');
		$('.ui-resizable-handle',$canvas).css({display:'none'});
	}
	var deleteSelected = function(){
		$canvas.find('.ui-selected').fadeOut(200,function(){
			$(this).find('img.ui-resizable').remove().end().remove();
		});
	}
	var deleteAll = function(){
		$canvas.find('.ui-wrapper').fadeOut(200,function(){
			$(this).find('img.ui-resizable').remove().end().remove();
		});
	}
	var cloneSelected = function(){
		var $clone = $canvas.find('.ui-selected img.ui-resizable').clone();
		if($clone.length) $clone.appendTo($canvas);
		else return false;
		var _pos = $canvas.find('.ui-selected').position();
		var $newItem = makeInteractive($clone);
		$newItem.css({position:'absolute',left:_pos.left,top:_pos.top,opacity:0})
		.animate({opacity:1,left:_pos.left+20, top:_pos.top+20},300);
	}
	var bringForward = function(){
		$canvas.find('.ui-selected').insertAfter($canvas.find('.ui-wrapper:last:not(.ui-selected)'));
	}
	
	// assign command click handlers
	$btnDelete.click(function(){deleteSelected();$(this).blur();return false;});
	$btnClearAll.click(function(){deleteAll();$(this).blur();return false;});
	$btnClone.click(function(){cloneSelected();$(this).blur();return false;});
	$btnForward.click(function(){bringForward();$(this).blur();return false;});
	
	$('.ui-wrapper').live('mousedown',function(){
		setSelected($(this));
	});
	
	// to support DEL & ENTER key
	$(document).keyup(function(e){
		var _k = e.which;
		// DELETE
		if(_k == 46) deleteSelected();
		if(_k == 32) cloneSelected();
		if(_k == 27) unSelectAll();
		if(_k == 13) bringForward();
	}).click(function(e){
		var $t = $(e.target);
		if(!($t.is('.ui-wrapper') || $t.parents().is('.ui-wrapper'))) unSelectAll();
	});
	// END: styleboard handler
	
	// Style Grid (starred boxes)
	$('div.StyleGrid .Starred').append('<div class="StarBadge" />');
	
	// Style slider
	$('div.StyleSlider').each(function(){
		var $me = $(this), $mask = $me.find('.Mask'), $left = $me.find('.ArrowLeft'), $right = $me.find('.ArrowRight');
		var $car = $mask.find('ul.StyleList'), $thumbs = $car.find('li a:first-child'), _count = $car.find('>li').length, _w = 563, _n = 1, _m = 1 /*(total thumbs)*/, _speed = 600;
		
		// adjust width of car
		$car.width(_count*_w).css({position:'absolute',left:0});
		
		function getPos(){ return parseInt($car.css('left'));}
		function updateButtons(){
			var _x = getPos();
			$left.removeClass('Disabled').find('img').css({opacity:1});
			$right.removeClass('Disabled').find('img').css({opacity:1});
			if(_x >= 0) $left.addClass('Disabled').find('img').css({opacity:.3});
			if(_x <= (_count-_m)*_w*-1) $right.addClass('Disabled').find('img').css({opacity:.3});
		}
		updateButtons();

		$left.click(function(){
			var $t = $(this);
			if($t.is('.Disabled') || $car.is(':animated')) return false;
			$car.animate({left:'+='+_w*_n+'px'},_speed,function(){
				updateButtons();
			});
			return false;
		});
		
		$right.click(function(){
			var $t = $(this);
			if($t.is('.Disabled') || $car.is(':animated')) return false;
			$car.animate({left:'-='+_w*_n+'px'},_speed,function(){
				updateButtons();
			});
			return false;
		});
		
	});
	
	// Photo gallery thumbnails
	function applySliderBestPhotos(){		
		$('div.SliderWrapper ul.BestPhotos').each(function(){
			var $me = $(this);
			//remove previous slicing
			$me.find('> div li').unwrap().removeClass('Slice');
			
			var $wrap = $me.parent('.SliderWrapper'), $li = $me.find('> li');
			var _rows = 4, _cols = 2, _liW = $li.width(), _liH = $li.height()+parseInt($li.css('padding-bottom'));
			
			if($wrap.is('.Rows-1')) _rows = 1;
			if($wrap.is('.Rows-2')) _rows = 2;
			if($wrap.is('.Rows-3')) _rows = 3;
			if($li.length <= _rows) {
			 $wrap.next('.Slider').remove();
				return;
			}
			$wrap.height((_liH*_rows)+15).css({overflow:'hidden'});
			$me.width(Math.ceil($li.length/_rows)*_liW).css({position:'absolute',right:0});
			$li.each(function(i){
				if(i%(_rows) == 0) $(this).addClass('Slice');
			}).filter('.Slice').each(function(){
				$(this).nextUntil('.Slice').andSelf().wrapAll('<div />');
			}).parent().css({float:'right'}).width(_liW);
			
			//remove previous slider
			$wrap.next('.Slider').remove();
			
			//create slider container
			$('<div class="Slider" />').insertAfter($wrap);
			
			setTimeout(function(){
			$wrap.each(function(){
				var $p = $(this), $slider = $p.next('div.Slider'), $ul = $p.find('ul.BestPhotos'), $li = $ul.find('>li');
				var _slideW = $slider.width();
				if(!$slider.is(':visible')) {
					$slider.parents('.TabPanel').css({display:'block'});
					_slideW = $slider.width();
					$slider.parents('.TabPanel').css({display:'none'});
				}
				var $track = $('<div />').width(_slideW - 40).css({position:'absolute',left:1,height:'100%',cursor:'pointer'});
				$slider.append($track).find('div').slider({
					value:100,
					step:1,
					slide:function(e,ui){
						var _pct = ((((ui.value-100)*-1)/100)).toFixed(2);
						$ul.css({right:'-'+($ul.width()-$wrap.width())*_pct+'px'});
						//$(".ui-slider-handle").css({right:'-'+100px})
					},
					start:function(){$('div.ContentWrapper').css({overflow:'hidden'})}
				});
			});
			},300);
		});
	}
		function applySliderRecentVideos(){		
		$('div.SliderWrapper ul.RecentVideos').each(function(){
			var $me = $(this);
			//remove previous slicing
			$me.find('> div li').unwrap().removeClass('Slice');
			
			var $wrap = $me.parent('.SliderWrapper'), $li = $me.find('> li');
			var _rows = 4, _cols = 2, _liW = $li.width(), _liH = $li.height()+parseInt($li.css('padding-bottom'));
			
			if($wrap.is('.Rows-1')) _rows = 1;
			if($wrap.is('.Rows-2')) _rows = 2;
			if($wrap.is('.Rows-3')) _rows = 3;
			if($li.length <= _rows) {
			 $wrap.next('.Slider').remove();
				return;
			}
			$wrap.height((_liH*_rows)+15).css({overflow:'hidden'});
			$me.width(Math.ceil($li.length/_rows)*_liW).css({position:'absolute',right:0});
			$li.each(function(i){
				if(i%(_rows) == 0) $(this).addClass('Slice');
			}).filter('.Slice').each(function(){
				$(this).nextUntil('.Slice').andSelf().wrapAll('<div />');
			}).parent().css({float:'right'}).width(_liW);
			
			//remove previous slider
			$wrap.next('.Slider').remove();
			
			//create slider container
			$('<div class="Slider" />').insertAfter($wrap);
			
			setTimeout(function(){
			$wrap.each(function(){
				var $p = $(this), $slider = $p.next('div.Slider'), $ul = $p.find('ul.RecentVideos'), $li = $ul.find('>li');
				var _slideW = $slider.width();
				if(!$slider.is(':visible')) {
					$slider.parents('.TabPanel').css({display:'block'});
					_slideW = $slider.width();
					$slider.parents('.TabPanel').css({display:'none'});
				}
				var $track = $('<div />').width(_slideW - 40).css({position:'absolute',left:1,height:'100%',cursor:'pointer'});
				$slider.append($track).find('div').slider({
					value:100,
					step:1,
					slide:function(e,ui){
						var _pct = ((((ui.value-100)*-1)/100)).toFixed(2);
						$ul.css({right:'-'+($ul.width()-$wrap.width())*_pct+'px'});
						
					},
					start:function(){$('div.ContentWrapper').css({overflow:'hidden'})}
				});
			});
			},300);
		});
	}
	// Photo gallery thumbnails
	function applySliderRecentPhotos(){		
	
		$('div.SliderWrapper ul.RecentPhotos').each(function(){
			var $me = $(this);
			//remove previous slicing
			$me.find('> div li').unwrap().removeClass('Slice');
			
			var $wrap = $me.parent('.SliderWrapper'), $li = $me.find('> li');
			var _rows = 4, _cols = 2, _liW = $li.width(), _liH = $li.height()+parseInt($li.css('padding-bottom'));		
			
			if($wrap.is('.Rows-2')) _rows = 2;			
			if($li.length <= _rows) {
			 $wrap.next('.Slider').remove();
				return;
			}
			$wrap.height((_liH*_rows)+15).css({overflow:'hidden'});
			$me.width(Math.ceil($li.length/_rows)*_liW).css({position:'absolute',right:0});
			$li.each(function(i){
				if(i%(_rows) == 0) $(this).addClass('Slice');
			}).filter('.Slice').each(function(){
				$(this).nextUntil('.Slice').andSelf().wrapAll('<div />');
			}).parent().css({float:'right'}).width(_liW);
			
			//remove previous slider
			$wrap.next('.Slider').remove();
	
			//create slider container
			$('<div class="Slider" />').insertAfter($wrap);

			setTimeout(function(){
			$wrap.each(function(){
				var $p = $(this), $slider = $p.next('div.Slider'), $ul = $p.find('ul.RecentPhotos'), $li = $ul.find('>li');
				var _slideW = $slider.width();				
				var $track = $('<div />').width(_slideW - 40).css({position:'absolute',left:1,height:'100%',cursor:'pointer'});
				$slider.append($track).find('div').slider({
					value:100,
					step:1,
					slide:function(e,ui){
						var _pct = ((((ui.value-100)*-1)/100)).toFixed(2);
						var _pct2 = ((((ui.value-30)*-1)/100)).toFixed(1);
						$ul.css({right:'-'+($ul.width()-$wrap.width())*_pct+'px'});
						//$(this).css({left:'-'+(3)*_pct2+'px'});
					},
					start:function(){$('div.ContentWrapper').css({overflow:'hidden'})}
				});
			});
			},300);
		});
		
	}
	function applySlider(){		
		$('div.SliderWrapper ul.GalleryPhotos,div.SliderWrapper ul.GalleryVideos').each(function(){
			var $me = $(this);
			//remove previous slicing
			$me.find('> div li').unwrap().removeClass('Slice');
			
			var $wrap = $me.parent('.SliderWrapper'), $li = $me.find('> li');
			var _rows = 4, _cols = 2, _liW = $li.width(), _liH = $li.height()+parseInt($li.css('padding-bottom'));
			
			if($wrap.is('.Rows-1')) _rows = 1;
			if($wrap.is('.Rows-2')) _rows = 2;
			if($wrap.is('.Rows-3')) _rows = 3;
			/*if($li.length <= _rows) {
			 $wrap.next('.Slider').remove();
				return;
			}*/
			$wrap.height((_liH*_rows)+15).css({overflow:'hidden'});
			if($li.length != 0) {
				$me.width(Math.ceil($li.length/_rows)*_liW).css({position:'absolute',right:0});
			}
			$li.each(function(i){
				if(i%(_rows) == 0) $(this).addClass('Slice');
			}).filter('.Slice').each(function(){
				$(this).nextUntil('.Slice').andSelf().wrapAll('<div />');
			}).parent().css({float:'right'}).width(_liW);
			
			//remove previous slider
			$wrap.next('.Slider').remove();
			
			//create slider container
			$('<div class="Slider" />').insertAfter($wrap);
			
			//setTimeout(function(){
			$wrap.each(function(){
				var $p = $(this), $slider = $p.next('div.Slider'), $ul = $p.find('ul.GalleryPhotos,ul.GalleryVideos'), $li = $ul.find('>li');
				var _slideW = $slider.width();
				if(!$slider.is(':visible')) {
					$slider.parents('.TabPanel').css({display:'block'});
					_slideW = $slider.width();
					$slider.parents('.TabPanel').css({display:'none'});
				}
				var $track = $('<div />').width(_slideW - 40).css({position:'absolute',left:1,height:'100%',cursor:'pointer'});
				
				var fChange = function(e,ui){
						var _pct = ((((ui.value-100)*-1)/100)).toFixed(2);
						$ul.css({right:'-'+($ul.width()-$wrap.width())*_pct+'px'});
						//$(".ui-slider-handle").css({right:'-'+100px})
				};
				
				$slider.append($track).find('div').slider({
					value:100,
					step:1,
					slide:fChange,
					change:fChange,
					start:function(){$('div.ContentWrapper').css({overflow:'hidden'})}
				});
			});
			//},300);
		});
	}
	if($('ul.GalleryTabs').length) 
		applySlider();
	else{
		setTimeout(function(){
			applySliderBestPhotos();				
		},200);
		}
	//assign this function to global scope
	applySliderGlobal1 = applySliderRecentPhotos;
	applySliderGlobal2 = applySliderBestPhotos;
	applySliderGlobal3 = applySliderRecentVideos;
	applySliderGlobal4 = applySlider;
	
		
	// Gallery tabs
	$('ul.GalleryTabs').each(function(){
		var $me = $(this), $li = $me.find('> li'), $panel = $me.nextAll('.TabPanel');
		var getSel = function(){return ($li.index($me.find('li.Selected')));}
		var showSelPane = function(){
			$panel.css({display:'none'}).eq(getSel()).css({display:'block'});
		}

		showSelPane();
		$li.find('a').click(function(){
			$li.removeClass('Selected');
			$(this).parent().addClass('Selected');
			showSelPane();
			return false;
		});
	});
	
	// Comments textarea
	$('textarea').css({resize:'none'})
	$('div.CommentsBlock textarea, fieldset.CelebForumField textarea, .ContactUsField textarea')
	.attr('maxlength',500)
	.bind('scroll',function(){
		var $t = $(this);
		if($t.scrollTop() > 0) $t.animate({height: $t.height()+$t.scrollTop()+3},0);
	})
	.each(function(){
		var $t = $(this);
		$t.scrollTop(2000);
		if($.browser.opera){
			$t.height($t.height()*3);
		}
		if($.browser.msie && $.browser.version == 8.0) $t.css({'text-align':'right'});
	})
	.keydown(function(e){
		var $t = $(this);
		if($t.val().length > parseInt($t.attr('maxlength'))) return false;
		//if(e.which == 8) $t.val($t.val().substring(0,$t.val().length));
		if(e.which == 46){
			$t.height(45);
			if($t.scrollTop() > 0) $t.animate({height: $t.height()+$t.scrollTop()+3},0);
		}
	})
	;
	

	
	// Sharing list
	$('.SharingList li:eq(0) a').attr('target','_blank');
	
	// Forum select
	$('fieldset.ForumSelect').each(function(){
		var $me = $(this), $pullDown = $me.prev('div.AdvancedSearch'), $btn = $me.find('input.SearchForumBtn2');
		
		$btn.toggle(
			function(){
				var _src = $(this).attr('src');
				_src = _src.replace('.gif','Active.gif');
				$pullDown.slideDown(300);
				$(this).attr('src',_src);
			},
			function(){
				var _src = $(this).attr('src');
				_src = _src.replace('Active.gif','.gif');
				$(this).attr('src',_src);
				$pullDown.slideUp(300);
			}
		);
	});
	
	// Forum select2
	$('fieldset.Search').each(function(){
		var $me = $(this), $pullDown = $me.next('div.TopAdvancedSearch').css({display:'none'}), $btn = $me.find('input.SearchButton2');
		
		$btn.toggle(
			function(){
				var _src = $(this).attr('src');
				_src = _src.replace('.gif','Active.gif');
				$pullDown.slideDown(300);
				$(this).attr('src',_src);
			},
			function(){
				var _src = $(this).attr('src');
				_src = _src.replace('Active.gif','.gif');
				$(this).attr('src',_src);
				$pullDown.slideUp(300);
			}
		);
	});
	
	// Zara Mag overlay
	$('ul.Nav0 li:eq(1) a').click(function(){
		
		var $t = $(this), _img = $t.attr('href'), _origPos = $t.offset();
		var _targetDim = {width:500,height:658};
		var _targetLoc = {left: $(window).width()/2 - _targetDim.width/2, top: $(window).height()/2 - _targetDim.height/2};
		
		if($('div.OverlayImage').length) {
			var $overlayImage = $('div.OverlayImage').css({display:'block',opacity:1});
			$overlayImage.animate({width:_targetDim.width, height:_targetDim.height, left:_targetLoc.left, top:_targetLoc.top},500);
			return false;
		}
	
		var $overlayImage = $('<div class="OverlayImage" />');

		$overlayImage.appendTo($('body'));
		$overlayImage.css({width:74,height:98,position:'absolute',left: _origPos.left-74,top: _origPos.top,zIndex:1000});
		var $img = $('<img />').css({position:'relative',zIndex:1});
		$img.appendTo($overlayImage).attr('src',_img);
		
		if(isIE6){
			var $iFix = $('<iframe />').css({position:'absolute',width:'100%',height:'100%',border:0,padding:'3px',margin:'-3px 0 0 -3px',zIndex:0}).prependTo($overlayImage);
		}
		
		var zoomImage = function(){
			$overlayImage.animate({width:_targetDim.width, height:_targetDim.height, left:_targetLoc.left, top:_targetLoc.top},500,function(){
				if(isIE6){
					$iFix.css({width:_targetDim.width,height:_targetDim.height});
				}
			});
			$img.attr('title','Click to close this image.');
			
			$('body').bind('click',function(){
				$overlayImage.animate({width:74,height:98,left: _origPos.left-74,top: _origPos.top, opacity:0},300,function(){
					$overlayImage.css({display:'none'});
				});
			});
		}
		
		if($.browser.msie && ($.browser.version == 7.0 || $.browser.version == 8.0)){
			zoomImage();
			return false;
		}
		
		$img.load(function(){
			zoomImage();
		});
		
		return false;
	});
	
	//Registration tool tip
	$('div.Title1').each(function(){
		$(this).find('a.TollTipAnchor').each(function(){
			var $t = $(this), _tipText = $t.find('img').attr('title');
			$t.find('img').attr('title','');
			var $tip = $('<div class="TollTipDiv" />');
			$tip.append('<div class="TollTipDivInner" />').find('.TollTipDivInner').append('<p class="TollTipPara">'+_tipText+'</p>');
			$tip.appendTo($t);
			$t.hover(
				function(){$tip.fadeIn();},
				function(){$tip.fadeOut();}
			);
			$t.click(function(){
				return false;
			});
		});
	});
	
	//Registration partially hidden fields
	$('div.Collapsable').css({clear:'both',display:'none'}).each(function(){
		var $me = $(this), $radio = $me.prev('fieldset').find('input[type=radio]');
		$radio.click(function(){
			if($(this).is('[value=Yes]')){
				//$me.slideDown();
				$me.fadeIn();
			}
			else $me.fadeOut();
		});
		$me.prev('fieldset').find('input[type=radio]:checked').click();
	});
	
	//Editorial Slider
	$('div.Editorial').each(function(){
		var $me = $(this), $mask = $me.find('.Mask'), $left = $me.find('.LeftArrowEditorial a'), $right = $me.find('.RightArrowEditorial a');
		var $car = $me.find('ul.EditorialGallery').css({position:'absolute'}), $thumbs = $car.find('li a'), _count = $car.find('img').length, _w = 114, _n = 4, _m = 5, _speed = 600;
		var $copy = $me.find('div.EditorialCopy').css({display:'none'}); $copy.eq(0).slideDown();
		
		// adjust width of car
		$car.width(_count*_w);
		
		function getPos(){ return parseInt($car.css('left'));}
		function updateButtons(){
			var _x = getPos() || 0;
			$left.removeClass('Disabled').find('img').css({opacity:1});
			$right.removeClass('Disabled').find('img').css({opacity:1});
			if(_x >= 0) $left.addClass('Disabled').find('img').css({opacity:.3});
			//updated opacity to 0 from .3 to hide arrows
			if(_x <= (_count-_m)*_w*-1 || _count <= _m) $right.addClass('Disabled').find('img').css({opacity:0});
		}
		updateButtons();
		
		$left.click(function(){
			var $t = $(this);
			if($t.is('.Disabled') || $car.is(':animated')) return false;
			$car.animate({left:'+='+_w*_n+'px'},_speed,function(){
				updateButtons();
			});
			return false;
		});
		
		$right.click(function(){
			var $t = $(this);
			if($t.is('.Disabled') || $car.is(':animated')) return false;
			$car.animate({left:'-='+_w*_n+'px'},_speed,function(){
				updateButtons();
			});
			return false;
		});
		
		$thumbs.find('img').hover(function(){
			$(this).css({opacity:.4});
		},function(){
			if($(this).parent().is('.Selected')) return;
			$(this).css({opacity:1});
		});
		$thumbs.click(function(){
			var n = $thumbs.index(this);
			var authorid = $thumbs.eq(n).attr("href");
			$thumbs.removeClass('Selected').find('img').css({opacity:1});
			$(this).addClass('Selected').find('img').css({opacity:.4});
			$copy.css({display:'none'}).eq(n).slideDown();
			$.get("/vgn-ext-templating-anazahra/overrides/jsp/anazahra_Editorial_Detail.jsp", 
             {
				authorid:authorid
              },function(data)
                {
                 $("#editorialteam").html(data);
                }
             ); 
			return false;
		});

	});
	
	//Blog archive explorer
	$('ul.ArchiveListing li').click(function(e){
		var $li = $(this);
		$li.siblings('li').removeClass('Expand');
		$li.toggleClass('Expand');
		e.stopPropagation();
	});
	
	//add class to MPU
	$('.BannerText').parent().addClass('MPU');
	
	//SendToFriend popups
	$('.SendtoFriend2 li a').click(function(){
		var $t = $(this), _url = $t.attr('href');
		var _popup = window.open(_url,'PopUp','width=450,height=440,top='+($(window).height()/2-220)+',left='+($(window).width()/2-225));
		if (window.focus) {_popup.focus()}
		return false;
	});
	
	//Fixes
	if($.trim($('.GoogleAddWrapper').text()) == '') {$('.GoogleAddWrapper').remove()};
	
	$('fieldset.RegisterField:last').addClass('RegisterFieldLast');
	$('fieldset.RegisterField input[type=radio]').next('span').addClass('SpanLabel');
	
	//Form validation
	$('div.ContactUsForm, div.Registration, div.SendFriend').each(function(){
		var $me = $(this), $submit = $me.find('input.ContactBtnImage, div.SolidBox input[type=image], div.DottedBox input[type=image], .SendtoFriend input[type=image]');
		var $req = $me.find('label span, label em');
		function validForm(){
			$me.find('.Error').removeClass('Error');
			$req.each(function(){
				var $field = $(this).parents('fieldset');
				var $input = $field.find('input[type=text]:visible, textarea:visible, input[type=password]:visible');
				if($.trim($(this).text()) == '*') {
					if($input.val() == '') $field.addClass('Error');
				}
				if($field.find('select:visible').length == 1){
					if($.trim($field.find('select').val()) == '') $field.addClass('Error');
				}
				if($field.find('select.DateSel:visible').length) {
					$field.find('select').each(function(){
						if($.trim($(this).val()) == '') $field.addClass('Error');
					});
				}
				if($field.find('input[type=radio]:visible').length){
					if(!$field.find('input[type=radio]:checked').length) $field.addClass('Error');
				}
			});
			
			if($me.is('.SendFriend')){
				$me.find('textarea').each(function(){
					if($.trim($(this).val()) == '') $(this).addClass('Error');
				});
			}
			
			//ContactUs Form Validation
			if($('div.ContactUsForm').is('.ContactUsForm')){
				var $error ='';
				var $field = $('#fromEmail').parents('fieldset');
				var $field2 = $('#confirmfromEmail').parents('fieldset');

				$field.removeClass('Error');
				$field2.removeClass('Error');
				
				if (isEmail($('#fromEmail').val()) == null){
					$field.addClass('Error');
				    $('#fromEmail').addClass('Error');
					$error = $error.concat("البريد  الإلكتروني الذي تحاولين استخدامه غير معرف\n");
				}
				if (isEmail($('#confirmfromEmail').val()) == null){
					$field2.addClass('Error');
					$('#confirmfromEmail').addClass('Error');
					$error = $error.concat("البريد  الإلكتروني الذي تحاولين استخدامه غير معرف\n");
				}
				if($('#fromEmail').val()!=$('#confirmfromEmail').val()){
				  $field.addClass('Error');
				  $field2.addClass('Error');
				  $('#fromEmail').addClass('Error');
				  $('#confirmfromEmail').addClass('Error');
				  $error = $error.concat("البريد الإلكتروني الذي أدخلته لا يطابق\n");
				}
				
				if($me.find('.Error').length) {
					if ($error != '') {
						alert("" + $error);
					}
					return false;
				} else if ($error != '')
				{
					alert("" + $error);
					return false;
				} else {
					$.get("/vgn-ext-templating-anazahra/overrides/jsp/anazahra_ContactUs_SendMail.jsp", 
					{
						deptMailId:$('#email').val(),
						userMailId:$('#confirmfromEmail').val(),
						mailBody:$('#emailMessage').val()
					});
					return true;
				}
				
			}
			
			/*Registration validations start*/
			if ($me.attr('class') == 'Registration')
			{
			
			var $error ='';
			var $field = $req.parents('fieldset');
			var $input = $field.find('input[id=propID_screen_name]:visible');
			if ($input.val()) {
			if(($input.val().length < 2 || $input.val().length > 30) || $input.val().indexOf(' ') > -1) {
				$error = $error.concat("اسم المستخدم يجب أن يتراوح بين 2-30 حرفا دون مسافات او رموز خاصة\n");
			} 
			/*else {
				var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
				for (var i = 0; i < $input.val().length; i++) {
				   if (iChars.indexOf($input.val().charAt(i)) != -1) {
					   $error = $error.concat("اسم المستخدم يجب أن يتراوح بين 2-30 حرفا دون مسافات او رموز خاصة\n");
					}
				}
			}*/
			}
			$input = $field.find('input[id=password1]:visible');
			if ($input.val()) {
			if($input.val().length < 2 || $input.val().length > 30) {
				$error = $error.concat("كلمة السر يجب ان تتراوح بين 2-30 حرفا\n");
			}
			}
			var $password2 = $field.find('input[id=password2]:visible');
			if($password2.val() != $input.val()) {
				$error = $error.concat("كلمة السر التي أدخلتيها غير مطابقة ، رجاء إدخال نفس كلمة السر في الخانتين\n");
			}
			$input = $field.find('input[id=propID_email]:visible');
			if ($input.val()) {
			if (isEmail($input.val()) == null){
				$error = $error.concat("البريد  الإلكتروني الذي تحاولين استخدامه غير معرف\n");
			}
			}
			$input = $field.find('input[id=mobile_country_code]:visible');
			if ($input.val()) {
				if ($input.val().match("^[0-9]+$") == null)
				{
					$error = $error.concat("رقم الهاتف النقال يجب ان يكون على سبيل المثال 1234567 50 971\n");
				} else {
					$input = $field.find('input[id=stdcode]:visible');
					if ($input.val().match("^[0-9]+$") == null) {
						$error = $error.concat("رقم الهاتف النقال يجب ان يكون على سبيل المثال 1234567 50 971\n");
					} else {
						$input = $field.find('input[id=propID_mobile_phone]:visible');
						if($input.val().length < 5 || $input.val().match("^[0-9]+$") == null) {
							$error = $error.concat("رقم الهاتف النقال يجب ان يكون على سبيل المثال 1234567 50 971\n");
						}
					}
				}
			}
			if ((! $('#propID_register').is(':hidden')) && (! $('#propID_register').attr('checked'))) {
				$error = $error.concat("رجاء اختيار خانة الشروط والأحكام");
			}
			if($me.find('.Error').length) return false;
			else if ($error != '')
			{
				alert("" + $error);
				return false;
			} else return true;
			}
			/*Registration validations End*/
			if($me.find('.Error').length) return false;
			else return true;
		}
		
		$submit.click(function(){
			return validForm();
		});
	});
	
	
	//CSS fixes
	if($.browser.opera){
		$('.Num2').each(function(){
			var _w = $(this).width();
			$(this).width(_w - 4);
		});
	}
	$('textarea,div.CommentsBlock textarea, fieldset.CelebForumField textarea').css({resize:'none'});
	if($.browser.msie || $.browser.opera) {
		$('fieldset.RegisterField input.Num2').css({width:175});
		$('fieldset.RegisterField div.PhoneNumber').css({width:281});
		$('fieldset.RegisterField select.YearSel').css({width:86});
	}
	
	
	});


//Added for Dynamically setting the Channel name to all the required DIV
$(document).ready(function() {
 if(js_primaryChannel !="" && js_primaryChannel!="Home" && js_primaryChannel!="generic channel"){
		$("div.Box").each(function(i){
			if(js_primaryChannel!="celebrity"){
			 $(this).removeClass('celebrity');
			}
			
			if(js_primaryChannel!="fashion"){
			  $(this).addClass(js_primaryChannel);
			}else{
			  $(this).addClass("Box"+js_primaryChannel);
			}
		});

		$("div.BoxLeft").each(function(i){
			if(js_primaryChannel!="celebrity"){
			 $(this).removeClass('celebrity');
			}
			
			if(js_primaryChannel!="fashion"){
			  $(this).addClass(js_primaryChannel);
			}else{
			  $(this).addClass("Box"+js_primaryChannel);
			}
		});
		
		$("div.BoxWrap").each(function(i){
			if(js_primaryChannel!="celebrity"){
			 $(this).removeClass('celebrity');
			}

			if(js_primaryChannel!="fashion"){
			  $(this).addClass(js_primaryChannel);
			}else{
			  $(this).addClass("Box"+js_primaryChannel);
			}
		});

		//$("div.Page").addClass(js_primaryChannel+"Page");
	}
	
	/*
	if(js_primaryChannel !="" && js_secondaryChannel!="" && js_primaryChannel=="generic channel"){
		if(js_secondaryChannel=="editorial team"){
		 $("div.Page").addClass("editorialPage");
		}
		else{
		$("div.Page").addClass(js_secondaryChannel.replace( /\s/g, "" )+"Page");
		}
	}
	*/
	
});

//Added for building link for Editioral page in Top links -Start
$(document).ready(function() {

	$("div.aboutuspopup span.Close").click(function(){
		$('#aboutuspopup').fadeOut();
	});
	
	var pos=$("#aboutus").position();
	var poppos=$('#aboutuspopup').position();
	$("#aboutus").hover(
		function(){
		$('#aboutuspopup').css('left',"84%");
		$('#aboutuspopup').css('top',"100%");
		$('#aboutuspopup').fadeIn();
	});
});
//Added for building link for Editioral page in Top links -End

//:: GLOBAL functions

function loadRatings() {
$('div.RatePlate').each(function(){
		var $t = $(this), $s = $t.parent().find('.SendCommentHolder a.SendComment').css({cursor:'pointer'});
		var _txt = $s.text();
		$t.append('<em>'+_txt+'</em>');
		if($s.is('.SendComment')){
			setTimeout(function(){
				var pos = $s.offset();
				$t.appendTo($('body')).css({left:pos.left-38, top:pos.top, zIndex:1000});
			},300);
		}
		else $t.prependTo($s);
		if(!$s.is('.SendComment')){
			$s.hover(
				function(){
					if($s.is('.Voted')) return;
					var pos = $s.offset();
					$t.css({left:pos.left-38, top:pos.top});
					$t.fadeIn(300);
				},
				function(){
					if($s.is('.Voted')) return;
					$t.fadeOut(300);
				}
			);
		}
		else{
			$s.mouseover(function(){
				if($s.is('.Voted')) return;
				var pos = $(this).offset();
				$t.css({left:pos.left-38, top:pos.top});
				$t.fadeIn(300);
			});
			$t.hover(function(){},function(e){
				if($s.is('.Voted')) return;
				$t.fadeOut(300);
			});
		}
		$t.find('a').click(function(){
			$t.css({display:'none'});
			$s.addClass('Voted').css({opacity:.5});
			return false;
		});
		$s.click(function(){
			return false;
		});
	});
}
$(document).ready(function() {
loadRatings();
});


// 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);
}
//Search Text 
function checkVal(s){
			var flagval = document.getElementById('searchflag').value;
			var txt = document.getElementById('searchKey').value;
			
			if(s=='f'){
				if(flagval=='no'){
					document.getElementById('searchKey').value = '';
					document.getElementById('searchflag').value = 'yes';
				}
			} else if(s=='b'){
				if(flagval=='yes' && txt==''){
					document.getElementById('searchKey').value = 'بحث';
					document.getElementById('searchflag').value = 'no';
				}
			}
		}
		
function searchTxt(){
	if(document.getElementById('searchflag').value == 'no'){
		//alert('do no search');
		return false;
	} else {
		document.getElementById('searchflag').value = 'yes';
		//alert('go to search');
	}
}

//setGallerySliderCallbacks - function for the scroll
function setGallerySliderCallbacks($gallery,$slider,$channelSelect,type,nr){

$gallery.data("nextPage",1);

//fGetNextPage - calls the ajax function to get the images and handles the result
var fGetNextPage = function(start,end) {
	
	// this is a pointer to the slider button
	var $sliderUI = $("a",$slider);
	var $imageList = $(".SliderWrapper>ul",$gallery);
	
	var startPage = 1;
	var endPage =  2;
	
	if (start >= 0){
		startPage = start;
		endPage = startPage +1;
	}
	
	if (end > startPage){
		endPage = end;
	}
	
	//console.log("get page " + start + ";"+end+ " [" + startPage+","+endPage+ "]" );
		
	$sliderUI.css('background','url("/deployedfiles/anazahra/CommonAssets/images/wait16trans.gif") no-repeat scroll 0 0 transparent');
	
	$.get("/vgn-ext-templating-anazahra/overrides/jsp/anazahra_gallery_page.jsp", {
    	channelName:$channelSelect.val(),
        selectedType: type,
		start: startPage,
		end: endPage
		
	},function(data){
		//ajax callback
		
		if(jQuery.trim(data)) {
			$gallery.data("nextPage", endPage +1);
			$imageList.append(data);
		}
		else {
			$gallery.data("bEnd", true);
		} 
		 
		//calculate new width
		var $li = $imageList.find('li');
		
		var _rows = nr, 
		_liW = $li.width();
		
		
		//console.log("nr images: ",_liW, "  size: ",$li.length, " size:",(Math.ceil($li.length/_rows)*_liW * 2) );		
		//if $li width is 0 this gallery is not visible
		$imageList.width(Math.ceil($li.length/_rows)*_liW * 2) ;
		
		//calculate new slider position
		
		if (parseInt($sliderUI.css("left")) < 10){
			$sliderUI.css("left","10%");
		}
				
		//Drawing is done
		$gallery.data("bDrawing", false);	    		
		$sliderUI.css('background','url("/deployedfiles/anazahra/CommonAssets/images/portal/button/SlideHandle.gif") no-repeat scroll 0 0 transparent');
		 
	}
	);
	
};////fGetNextPage 

//fSliderChange - handles the slider change
 var fSliderChange = function(event,ui) {
	
	if ( $gallery.data("bDrawing") || $gallery.data("bEnd")) 
		return;
		
	var sliderposition = (10 - divide(ui.value,10));
	//console.log("slider",sliderposition);
		
	var nextPage = $gallery.data("nextPage");
	
	//console.log ("slider " +sliderposition + " [" + nextPage); ;
	
	if (sliderposition >= nextPage || sliderposition >= 10){
		sliderposition == nextPage ? sliderposition ++ : "";
		$gallery.data("bDrawing",true);
		fGetNextPage(nextPage,sliderposition);
	}
	
};//fSliderChange

	
$slider.bind("slidechange", fSliderChange);
$slider.bind("slide", fSliderChange);

$channelSelect.change(function() {

	var $sliderUI = $("a",$slider);
	var $imageList = $(".SliderWrapper>ul",$gallery);

	$imageList.empty();
	$imageList.css("right","0");
	

	$gallery.data("nextPage",1);
	$sliderUI.css("left","100%");

	fGetNextPage(0,1);
});

}//setGallerySliderCallbacks

// traditional pagination for galleries

function getPage(pageNumber, type, channel, style){
	if (type == 'Photos'){
	  	$("#gallery_photos").prepend("<img src='/deployedfiles/anazahra/CommonAssets/images/azwait.gif' style='position:absolute; top:35%; left:50%'/>");
	} else {
		$("#gallery_videos").prepend("<img src='/deployedfiles/anazahra/CommonAssets/images/azwait.gif' style='position:absolute; top:35%; left:50%'/>");
	}
	$.get('/vgn-ext-templating-anazahra/overrides/jsp/anazahra_gallery_page.jsp', {'page': pageNumber, 'channelName': channel , 'selectedType' : type, 'style' : style}, function(data) {
		if (type == 'Photos'){
		  	$("#gallery_photos").html(data);
		} else {
			$("#gallery_videos").html(data);
		}
	});
}

function showPage(newIndex, namespace) {
	$('.' + namespace + '-gallery-page').each(function() {
		$(this).hide("slow");
	});
	$('li.' + namespace + '-navpage','ul#' + namespace + '-pagination').removeClass("vSelected");
	$('#' + namespace + '-page-'+newIndex).show("slow");
	$('ul#' + namespace + '-pagination').attr("selected", newIndex);
	$('li.' + namespace + '-navpage[page=' + newIndex + ']','ul#' + namespace + '-pagination').addClass("vSelected");
	if (newIndex == 1) {
		$('li.' + namespace + '-vnavbutton[direction=previous]','ul#' + namespace + '-pagination').css("visibility", "hidden");
	} else {
		$('li.' + namespace + '-vnavbutton[direction=previous]','ul#' + namespace + '-pagination').css("visibility", "visible");
	}
	
	if (newIndex == 7) {
		$('li.' + namespace + '-vnavbutton[direction=next]','ul#' + namespace + '-pagination').css("visibility", "hidden");
	} else {
		$('li.' + namespace + '-vnavbutton[direction=next]','ul#' + namespace + '-pagination').css("visibility", "visible");
	}
	$('li.' + namespace + '-navpage','ul#' + namespace + '-pagination').addClass('vnavcursor');
	$('li.' + namespace + '-navpage[page=' + newIndex + ']','ul#' + namespace + '-pagination').removeClass("vnavcursor");
	
}

function centerNavigation(namespace){
	var index = parseInt($('ul#' + namespace + '-pagination').attr("selected"));
	var beginIndex = Math.max(index - 2, 1);
	var endIndex = Math.min(index + 2, 7);
	if (index < 3) {
		endIndex = 5;
		beginIndex = 1;
	}
	if (index > 5) {
		beginIndex = 3;
		endIndex = 7;
	}
	$('.' + namespace + '-navpage').hide();
	for (j = endIndex; j >= beginIndex ; j-- ) {
		$('li.' + namespace + '-navpage[page='+j+']','ul#' + namespace + '-pagination').show();
	}
		
}


