/*############################################ functions.js ##########################################*/

///####################    Eng.MOMTAZ     ##################

/*-----------------------------------------------------------------------------------------------*/

//Browser detect script origionally created by Peter Paul Koch at http://www.quirksmode.org/
function getBrowserInfo() {

/*-------------------------------GLOBAL VARIABLES------------------------------------*/
var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;

	//alert("info");
	if (checkIt('konqueror')) {
		browser = "Konqueror";
		OS = "Linux";
	}
	else if (checkIt('safari')) browser 	= "Safari"
	else if (checkIt('omniweb')) browser 	= "OmniWeb"
	else if (checkIt('opera')) browser 		= "Opera"
	else if (checkIt('webtv')) browser 		= "WebTV";
	else if (checkIt('icab')) browser 		= "iCab"
	else if (checkIt('msie')) browser 		= "Internet Explorer"
	else if (!checkIt('compatible')) {
		browser = "Netscape Navigator"
		version = detect.charAt(8);
	}
	else browser = "An unknown browser";

	if (!version) version = detect.charAt(place + thestring.length);

	if (!OS) {
		if (checkIt('linux')) OS 		= "Linux";
		else if (checkIt('x11')) OS 	= "Unix";
		else if (checkIt('mac')) OS 	= "Mac"
		else if (checkIt('win')) OS 	= "Windows"
		else OS 								= "an unknown operating system";
	}
}

function checkIt(string) {
	/*-------------------------------GLOBAL VARIABLES------------------------------------*/
var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;

	place = detect.indexOf(string) + 1;
	thestring = string;
	//alert(place);
	return place;
}

	//============= Select Link
function SelectLink(id,count)
{
	for(var i=1;i<=count;i++)
	{
		var Link=document.getElementById('Link'+i);
		
		if(id==i)
		{
			Link.className="homelink2";
		   
		}
		else
			Link.className="homelink";
				
	   
	}
}
/*---------forIconActive----*/
function SelectLink2(id,count)
{
	for(var i=1;i<=count;i++)
	{
		
		var Link=document.getElementById('icon'+i);
		if(id==i)
		{
		    Link.className="link-selected-pic";
		}
		else
			Link.className="link-selected-pic2";	
	   
	}
}
/*---------forIconActive----*/
function SelectLinkTopHome(id,count)
{
	for(var i=1;i<=count;i++)
	{
		
		var Linka=document.getElementById('linka'+i);
		if(id==i)
		{
		    Linka.className=('Linkact'+i);
		}
		else
			Linka.className='Link'+i;	
	   
	}
}
/*----------------vedioArchiveNewsACtive----*/
function SelectLinkDownHome(id,count)
{
	for(var i=1;i<=count;i++)
	{
		
		var Linkd=document.getElementById('Linkd'+i);
		if(id==i)
		{
		    Linkd.className=('linkdselect'+i);
		}
		else
			Linkd.className='linkd'+i;	
	   
	}
}


	//-------------hide and show menu
function showCompMenu()
{
	var galaryMenu=document.getElementById('galaryMenu');
	galaryMenu.style.display='block';
	
}
function HideCompMenu()
{
	var galaryMenu=document.getElementById('galaryMenu');
	galaryMenu.style.display='none';
}
	//-------------hide and show services menu
function showServMenu()
{
	var visitorMenue=document.getElementById('visitorMenue');
	window.clearTimeout(t);
	visitorMenue.style.display='block';
	
}
function HideServMenu()
{
	var visitorMenue=document.getElementById('visitorMenue');
	visitorMenue.style.display='none';
}
//-------------hide and show aboutus menu
function showaboutMenu()
{
	var newsMenu=document.getElementById('newsMenu');
	newsMenu.style.display='block';
	
}
function HideaboutMenu()
{
	var newsMenu=document.getElementById('newsMenu');
	newsMenu.style.display='none';
}

function DoNothing()
{
 var i=i+2;	
}


function validate(id)
{
var age=document.getElementById(id).value;

if (age>0)
 return true;
else
 {
 alert("The no of rooms must be a number");
 return false;
 }

 }
//###############LoadModule(page form other web)################
 Montada=function(proxy_url,module,submodule,location,form)
		{ 
				var url='proxy.php?proxy_url='+proxy_url;
				var now = new Date();
				var exitTime = now.getTime();
				var data='&someParameter='+exitTime;
				document.getElementById(location).innerHTML="<table border='0' width='100%' height='100%' align='center' ><tr valign='middle'><td height='100%' align='center' valign='middle'><img valign='middle' src='images/working.gif'></td></tr></table>";
				$.ajax({
			   type: "POST",
			   url: url,
			   dataType: "html",
			   data: data,
			   success: function(html){
					LoadModule(module,submodule,location,'&response='+html,form)
				}
				
			 });
				//alert($response);
};
//'&response='+html,''

/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "-";
var minYear=0000;
var maxYear=9999;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   }
   return this
}

function IsDate(dtStr,curDay,curMon,curYear){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	//alert(day);
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : dd-mm-yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
return true
}

ValidateDate=function(input,day,month,year){
	var dt=input;
   // alert(input.value);
	if (IsDate(dt.value)==false){
		dt.focus()
		return false
	}
    return true
 }
// Validate Date functions End
function ValidateEmailScripts(elem,error,type,id)
	{
		Email=elem.value/*+'@'+domain*/;
		//alert(Email);
		//var Ret=Email.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]$/i);	
		var Ret=Email.match(/^[a-z]([a-z0-9]|_|-|.)+@([a-z0-9]|-|_)+(\.([a-z0-9]){2,4}){1,2}$/i);  		
		if(!type){
			if(Ret==null){
				alert(error);
				elem.focus();
				return false;
			}
		} else {
			var d=document.getElementById(id);
	  		var cross=document.getElementById(elem.id+'_cross');
			if(Ret==null){
				d.innerHTML=error;
      			cross.style.display='inline';
				return false;
			} else {
				d.innerHTML='';
     			cross.style.display='none';
    		}
		}
		return true;
	}

function compare(elem,next,error,type,id){
	if(!type){
			if(elem.value==next){
				alert(error);
				elem.focus();
				return false;
			}
	} else {
		var d=document.getElementById(id);
        var cross=document.getElementById(elem.id+'_cross');
		if(elem.value==next){
				d.innerHTML=error;
                cross.style.display='inline';
				return false;
		} else {
				d.innerHTML='';
                cross.style.display='none';
        }
	}
	return true;
}
/*******************************/
function isURL(elem,error,type,id) {
	var d=document.getElementById(id);
	var cross=document.getElementById(elem.id+'_cross');
	var urlStr=elem.value;
	
	if (urlStr.indexOf(" ") != -1) {
		if(!type){
			alert("Spaces are not allowed in a URL");
			elem.focus();
		} else {
			d.innerHTML="Spaces are not allowed in a URL";
			cross.style.display='inline';
		}	
		return false;
	} 
	
	if (urlStr == "" || urlStr == null || urlStr == "http://") {
		return true;		
	}
	

	urlStr=urlStr.toLowerCase();

	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var atom=validChars + '+';
	var urlPat=/^http:\/\/(\w*)\.([\-\+a-z0-9]*)\.(\w*)/;
	var matchArray=urlStr.match(urlPat);

	if (matchArray==null) {
		if(!type){
			alert("The URL seems incorrect \ncheck it begins with http://\n and it has 2 .'s");
			elem.focus();
		} else {
			d.innerHTML="The URL seems incorrect \ncheck it begins with http://\n and it has 2 .'s";
			cross.style.display='inline';
		}	
		return false;
	}
	

	var user=matchArray[2];
	var domain=matchArray[3];

	for (i=0; i<user.length; i++) {

		if (user.charCodeAt(i)>127) {
			if(!type){
				alert("This domain contains invalid characters.");
				elem.focus();			
			} else {
				d.innerHTML="This domain contains invalid characters.";
				cross.style.display='inline';
			}
			return false;
		}
	}

	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i) > 127) {
			if(!type){
				alert("This domain name contains invalid characters.");
				elem.focus();			
			} else {
				d.innerHTML="This domain name contains invalid characters.";
				cross.style.display='inline';
			}	
			return false;
		}
	}

	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;

	for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat) == -1) {
			alert("The domain name does not seem to be valid.");
			elem.focus();
			return false;
		}
	}
	d.innerHTML='';
	cross.style.display='none';

	return true;
} 


/*******************************/
function highlight_wiz_Final(selected,total,menu)
{
	// show left menu and hide other
	document.getElementById('mail_list_area').style.display='none';
   	document.getElementById('write_message_area').style.display='none';
	//document.getElementById('send_process_area').style.display='none';

	document.getElementById(menu+'_area').style.display='block';
	//alert(menu);
	for(i=1;i<=total;i++)
	{
		if(i<=selected) 
			{
				document.getElementById(menu+i).style.background='url(images/try-bar.gif)';// header top
				if(i==selected)
				 {
					document.getElementById(menu+'_step'+i).className='lighter';//left menu
					document.getElementById(menu+'_'+i).className='selected';// header arrow
				 }
				else
				 {
					document.getElementById(menu+'_step'+i).className='notlight';//left menu
					document.getElementById(menu+'_'+i).className='';
				 }
			} else {
				document.getElementById(menu+'_step'+i).className='notlight';
				document.getElementById(menu+i).style.background='#7DD0FC';
				document.getElementById(menu+'_'+i).className='';				
			}
	}
	heights();
} // end of highlight_wiz_Final function

////////////////////////  close all left menu     //////////////////////
	function CloseAll() {
			//alert('called');
            if(document.getElementById('mail_list_area'))
    			document.getElementById('mail_list_area').style.display='none';
            if(document.getElementById('write_message_area'))
    			document.getElementById('write_message_area').style.display='none';
	}
/////////////  hihlight and clear left top (login area) ///////////
    function ClearLeft(subMod) {
        var link1=document.getElementById('user_link1');
        var link2=document.getElementById('user_link2');
        var link3=document.getElementById('user_link3');
        var link4=document.getElementById('user_link4');
        var link5=document.getElementById('user_link5');
        if(link1 && link2 && link3 && link4 && link5)
        switch(subMod){
         case 'Load_updateform':
                link1.className='user_link1_ac';
                link1.rel=1;
                link2.className='user_link';
                link2.rel=0;
                link3.className='user_link';
                link3.rel=0;
                link4.className='user_link';
                link4.rel=0;
                link5.className='user_link';
                link5.rel=0;
            break;
         case 'Load_updatepass':
                link2.className='user_link1_ac';
                link2.rel=1;
                link1.className='user_link';
                link1.rel=0;
                link3.className='user_link';
                link3.rel=0;
                link4.className='user_link';
                link4.rel=0;
                link5.className='user_link';
                link5.rel=0;
            break;
         case 'finish_shopping':
                link3.className='user_link1_ac';
                link3.rel=1;
                link2.className='user_link';
                link2.rel=0;
                link1.className='user_link';
                link1.rel=0;
                link4.className='user_link';
                link4.rel=0;
                link5.className='user_link';
                link5.rel=0;
            break;
         case 'myProcess':
                link4.className='user_link1_ac';
                link4.rel=1;
                link2.className='user_link';
                link2.rel=0;
                link3.className='user_link';
                link3.rel=0;
                link1.className='user_link';
                link1.rel=0;
                link5.className='user_link';
                link5.rel=0;
            break;
         case 'myHistory':
                link5.className='user_link1_ac';
                link5.rel=1;
                link2.className='user_link';
                link2.rel=0;
                link3.className='user_link';
                link3.rel=0;
                link4.className='user_link';
                link4.rel=0;
                link1.className='user_link';
                link1.rel=0;
            break;
         default :
                link1.className='user_link';
                link1.rel=0;
                link2.className='user_link';
                link2.rel=0;
                link3.className='user_link';
                link3.rel=0;
                link4.className='user_link';
                link4.rel=0;
                link5.className='user_link';
                link5.rel=0;
        }

    }
////////////////////////  select code in list_plugin     //////////////////////
	function SelectTextArea() {
			document.getElementById('PluginText').select(); 
			document.getElementById('PluginText').focus();
	}

////////////////////////  Edit In place Functions   ///////////////////
function fixInputSizes() {
 	var iT = document.getElementsByTagName('input');
	/*for(i=0; i<iT.length;i++){
		if(iT[i].className == 'edit'){
			iT[i].style.width = iT[i].value.length*6+38+'px'; 
		}
	}*/
 }
function checkLength(o) { 
		//o.style.width = o.value.length*6+38+'px'; 
}
function changeClass(id, action) {
       if (action=="hide") {
            $(id).className = "show";
            save(id);
       } else {
       	
       	    $('status').innerHTML ='';
            $(id).className = "edit";
			$(id).readOnly = false;
       }
}

function SelectProduct()
	{
		var product_ID = $F('lists');
		var url = 'mail_list_update_name.php';
		var pars = 'pID=' + product_ID;
		//alert("call made");
		
var myAjax = new Ajax.Request( url, { method: 'get', parameters: pars, onComplete: showResponse });

	}
	
	function cue_edit(id)
	{
		var product_ID = id;
		alert(id);
		//var y = $F('lstYears');
		var url = 'mail_list_update_name.php';
		var pars = 'pID=' + product_ID; // + '&year=' + y;
		alert("call made");
		
		var myAjax = new Ajax.Request( url, { method: 'get', parameters: pars, onComplete: showResponse });

	}
	
	

	function showResponse(originalRequest)
	{
		//put returned XML in the textarea
		//$('result').value = originalRequest.responseText;
		var rXML = originalRequest.responseXML;
		
		var pIDs = rXML.getElementsByTagName('pID').item(0);
		var pID = pIDs.firstChild.data;
		var values = rXML.getElementsByTagName('value').item(0);
		var value = values.firstChild.data;
		
		var pidField = '<input type = "hidden" id="pID" value="'+pID+'"></input>';
		var textField = '<input type = "text" id="name" size="30" value="'+value+'"></input">';
		var save = '<br><a href="javascript:save(ddiv);">Save</a>';
		
		//alert(pID);
		//alert(value);
		
	    //pID = rXML.GetElementById("pID");
		$(pID).innerHTML = pidField+textField+save;
		//alert(originalRequest.responseText);
	}

	function save(id){

	var new_content	=  $F(id);
	var success	= function(t){ 
		//alert('update succeeded'); 
		$('ddiv').innerHTML = t.responseText + 'supposed to be here'; 
	}
	var failure	= function(t){ alert('update failed'); }
	//this is setup for localhost. make sure and change this for your installation. 
	//note:  if you put http://www.domainname.com and call the page http://domainname.com
	//this will not work
  	var url = 'mail_list_update_name.php';
	var pars = 'edit=go&list_name='+new_content+'&list_id='+id;

	//$('ddiv').innerHTML = 'updating....';
	//alert(url);
	var myAjax = new Ajax.Request(
			url, 
			{
				method: 'get', 
				parameters: pars, 
				onComplete: update_page
			}	);
	}
	
	function update_page(originalRequest) {
	
	var rXML = originalRequest.responseXML;
	var pIDs = rXML.getElementsByTagName('pID').item(0);
	var pID = pIDs.firstChild.data;
	//alert('i have ' + pID + ' to update');
	var values = rXML.getElementsByTagName('value').item(0);
	var value = values.firstChild.data;
	//alert('i have ' + value + 'as a return value');
	
	$(pID).innerHTML = value;	
	$('status').innerHTML = 'update complete';
		
	}

	function select() { 
		
		$('select').innerHTML = 'load menu';
		
	}
///////////////  Edit In place end   //////////////	

///#################    Eng.RANIA    #####################

/*******************************/
function selectCat(num,total)
{
	for(j=0;j<total;j++)
		{
		document.getElementById('catText'+(j+1)).className='catNormal';
		if(j==0)
			document.getElementById('sholder'+j).className='catNormal_left';
		else 
			document.getElementById('sholder'+j).className='catNormal_mid';
		if(j==(total-1))
			document.getElementById('sholder'+(j+1)).className='catNormal_right';
		}//for
	document.getElementById('catText'+num).className='catSelected';
	if(num==1)
		document.getElementById('sholder'+(num-1)).className='catSelected_start';
	else
		document.getElementById('sholder'+(num-1)).className='catSelected_midleft';
	if(num==total)
		document.getElementById('sholder'+num).className='catSelected_end';
	else
		document.getElementById('sholder'+num).className='catSelected_midright';
}

function addValues()
{

var x=document.getElementsByName('ch');
var x=document.getElementsByName('ch');
if(x.length>=6)
	document.getElementById('btn_id5').disabled='disabled';
else
	document.getElementById('btn_id5').disabled='';

values="";
	for(i=0;i<x.length;i++)
	{
	if(x[i].checked==true)
		{
		
		if (values=="")values+=x[i].value;
		else values+=","+x[i].value;
		}
	else if( x[i].checked==false)
		{
		
		if (values=="")values+=0;
		else values+=","+0;
		}	
	}//for
	
		document.getElementById('attached_ch').value=values;
	
}

function getFile(filename,formName,pars)
	{
		
		var url="readFile.php";
		var now = new Date();
		var exitTime = now.getTime();
		var data="filename="+filename+"&someParameter="+exitTime;
		if(pars!='')data+=pars;
		
		
			if(formName)
			 data+="&"+Form.serialize(document.getElementById(formName));	
			else
			 data+="&"+Form.serialize(document.getElementById('messageForm4'));
			
	if(filename=='')	var location='write_msg_content';
	else { var location='mes_content';	 $('mes_content').innerHTML='';}
	
     var myAjax = new Ajax.Updater(
			location, 
			url, 
			{
				method: 'post', 
				parameters: data,
				onComplete: showResponse,
				onLoading :showWaiting,
				evalScripts:true,
				asynchronous:true
			} );
	function showResponse(originalRequest)
	{ 
	
	//document.getElmentById("mes_content").value=originalRequest.responseText;
	//LoadModule('Write_message','step3_stat','','','messageForm3'); 
	}
		
function showWaiting()
	{
	document.getElmentById(location).innerHTML="<table border=0 width='100%' height='380' align='center' ><tr valign='middle'><td height='380' align='center' valign='middle'><img valign='middle' src='images/loading.gif'></td></tr></table>";	
	}
	
	}




	

function XMLData(pars)
	{
		
		var url="messages/templates/dyn_temp1.php";
		var now = new Date();
		var exitTime = now.getTime();
		var data="pars="+pars+"&someParameter="+exitTime;
		 var xx=true;
		var location="results";
		/*if(pars){
			xx=false;
			
			var url="Write_message-replace.php";
			data+="&"+Form.serialize(document.getElementById('dynamicMes'));

		}*/
		
     var myAjax = new Ajax.Updater(
			location, 
			url, 
			{
				method: 'post', 
				parameters: data,
				onComplete: showResponse,
				onLoading :showWaiting,
				evalScripts:true,
				asynchronous:true
			} );
	function showResponse(originalRequest)
	{ 
	
	
	//document.getElementById(location).innerHTML=eval(originalRequest.responseText);
	
	//XMLData('1');
	
	
	}
		
function showWaiting()
	{
	document.getElmentById(location).innerHTML="<table border=0 width='100%' height='380' align='center' ><tr valign='middle'><td height='380' align='center' valign='middle'><img valign='middle' src='images/loading.gif'></td></tr></table>";	
	}
	
	}


///####################    Eng.RASHA     ##################
// Password strength meter v1.0
// Matthew R. Miller - 2007
// www.codeandcoffee.com
// Based off of code from  http://www.intelligent-web.co.uk
// Settings
// -- Toggle to true or false, if you want to change what is checked in the password
var bCheckNumbers = false;
var bCheckUpperCase = false;
var bCheckLowerCase = false;
var bCheckPunctuation = false;
var bCheckCompination = true;
var nPasswordLifetime = 365;
// Check password
function checkPassword(strPassword)
{
	// Reset combination count
	nCombinations = 0;
	
	// Check numbers
	if (bCheckNumbers)
	{
		strCheck = "0123456789";
		if (doesContain(strPassword, strCheck) > 0) 
		{ 
        		nCombinations += strCheck.length; 
    		}
	}
	
	// Check upper case
	if (bCheckUpperCase)
	{
		strCheck = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		if (doesContain(strPassword, strCheck) > 0) 
		{ 
        		nCombinations += strCheck.length; 
				//alert('the password can not contain upper case character');
    		}
	}
	
	// Check lower case
	if (bCheckLowerCase)
	{
		strCheck = "abcdefghijklmnopqrstuvwxyz";
		if (doesContain(strPassword, strCheck) > 0) 
		{ 
        		nCombinations += strCheck.length; 
    		}
	}
	
	// Check punctuation
	if (bCheckPunctuation)
	{
		strCheck = ";:-_=+\|//?^&!.@$#*()%~<>{}[]";
		if (doesContain(strPassword, strCheck) > 0) 
		{ 
        		nCombinations += strCheck.length; 
    		}
	}
	// Check compination
	/*if (bCheckCompination)
	{
		strCheck = ";:-_=+\|//?^&!.@$#*()%~<>{}[]abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		if (doesContain(strPassword, strCheck) > 0) 
		{ 
        		nCombinations += strCheck.length; 
    		}
	}*/
	// Calculate
	// -- 500 tries per second => minutes 
    	var nDays = ((Math.pow(nCombinations, strPassword.length) / 500) / 2) / 86400;
 
	// Number of days out of password lifetime setting
	var nPerc = nDays / nPasswordLifetime;
	
	return nPerc;
}
 
// Runs password through check and then updates GUI 
function runPassword(strPassword, strFieldID) 
{
	// Check password
	nPerc = checkPassword(strPassword);
	
	 // Get controls
    	var ctlBar = document.getElementById(strFieldID + "_bar"); 
    	var ctlText = document.getElementById(strFieldID + "_text");
    	if (!ctlBar || !ctlText)
    		return;
    	
    	// Set new width
    	var nRound = Math.round(nPerc * 100);
	if (nRound < (strPassword.length * 5)) 
	{ 
		nRound += strPassword.length * 5; 
	}
	if (nRound > 100)
		nRound = 100;
    	ctlBar.style.width = nRound + "%";
 
 	// Color and text
 	if (nRound > 95)
 	{
 		strText = "Very Secure";
 		strColor = "#3bce08";
 	}
 	else if (nRound > 75)
 	{
 		strText = "Secure";
 		strColor = "orange";
	}
 	else if (nRound > 50)
 	{
 		strText = "Mediocre";
 		strColor = "#ffd801";
 	}
 	else
 	{
 		strColor = "red";
 		strText = "Insecure";
 	}
	ctlBar.style.backgroundColor = strColor;
	ctlText.innerHTML = "<span style='color: " + strColor + ";'>" + strText + "</span>";
}
 
// Checks a string for a list of characters
function doesContain(strPassword, strCheck)
 {
    	nCount = 0; 
 
	for (i = 0; i < strPassword.length; i++) 
	{
		if (strCheck.indexOf(strPassword.charAt(i)) > -1) 
		{ 
	        	nCount++; 
				
		} 
	} 
 
	return nCount; 
} 
/********/
/*function confirm_password(pass,cpass){
	if(pass=='' )
	document.getElementById('err_pass').innerHTML="";
	else if(pass==cpass)
	document.getElementById('err_pass').innerHTML="<img src='images/active.gif'><span class='err'>Pass Match</span>";
	else if (pass !=cpass)
	document.getElementById('err_pass').innerHTML="<img src='images/inactive.gif'><span class='err'>Pass Do not match</span>";
	
	}*/
	/***********Function for sign up ***************/
	function getElementsByClassName(className, tag, elm){
	var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
	var tag = tag || "*";
	var elm = elm || document;
	var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	var current;
	var length = elements.length;
	//alert(testClass);
	for(var i=0; i<length; i++){
		current = elements[i];
		if(testClass.test(current.className)){
			returnElements.push(current);
		}
	}
	return returnElements;
}

function addClassName(elm, className){
    var currentClass = elm.className;
    if(!new RegExp(("(^|\\s)" + className + "(\\s|$)"), "i").test(currentClass)){
        elm.className = currentClass + ((currentClass.length > 0)? " " : "") + className;
    }
    return elm.className;
}

function removeClassName(elm, className){
    var classToRemove = new RegExp(("(^|\\s)" + className + "(\\s|$)"), "i");
    elm.className = elm.className.replace(classToRemove, "").replace(/^\s+|\s+$/g, "");
    return elm.className;
}

function hasClass(el, c) {
  if (!el || !el.className.length) return;
  var bits = el.className.split(' '), has = false;
  for (var j = 0; j < bits.length; j++) if (bits[j] === c) has = true;
  return has;
}

function activateThisColumn(column) {
  var table = document.getElementById('pricetable');
  var form = document.getElementById('formcontainer');
//give width to the table
table.style.width='200px';
  // first, remove the 'on' class from all other th's
  var ths = table.getElementsByTagName('th');
  for (var g=0; g<ths.length; g++) {
    removeClassName(ths[g], 'on');
    if (!hasClass(ths[g],'side')) {
      ths[g].style.display = 'none';
	   ths[g].style.width = '0px';
    }
  }
  // then, remove the 'on' class from all other td's
  var tds = table.getElementsByTagName('td');
  for (var m=0; m<tds.length; m++) {
    removeClassName(tds[m], 'on');
    if (!hasClass(tds[m],'side')) {
      tds[m].style.display = 'none';
	  tds[m].style.width = '0px';
    }
  }

  // now, add the class 'on' to the selected th
  var newths = getElementsByClassName(column, 'th', table);
 
  for (var h=0; h<newths.length; h++) {
	document.register.member.value=newths[h].innerHTML;
    addClassName(newths[h], 'on');
    newths[h].style.display = '';
	 newths[h].style.width = '103px';
    // not all browsers like display = 'block' for cells
  }
    // and finally, add the class 'on' to the selected td
  var newtds = getElementsByClassName(column, 'td', table);
  for (var i=0; i<newtds.length; i++) {
    addClassName(newtds[i], 'on');
    newtds[i].style.display = '';
	 newtds[i].style.width = '85px';
    // not all browsers like display = 'block' for cells
  }
  
  // show the form!
  form.style.display = 'block';
}

function hideTheForm() {
	// get the form
	var form = document.getElementById('formcontainer');
	// hide the form
	form.style.display = 'none';
	//to clear error area
/*	document.getElementById('err_reg').innerHTML='';
	document.getElementById('err_domain').innerHTML='';
	document.getElementById('verify_domain').innerHTML='';
	document.getElementById('err_pass').innerHTML='';
	document.getElementById('err_mail').innerHTML='';
	document.getElementById('err_code').innerHTML='';*/
	// now get the hidden table cells and show them again
	var table = document.getElementById('pricetable');
	table.style.width='';
	var tds = table.getElementsByTagName('td');
	for (var i=0; i<tds.length; i++) {
		tds[i].style.display = '';
		tds[i].style.width = '80px';
	}
	var ths = table.getElementsByTagName('th');
	for (var k=0; k<ths.length; k++) {
		ths[k].style.display = '';
		ths[k].style.width = '100px';
	}
}


/**************Select All************/
function HighlightAll(theField) {
var tempval=eval("document."+theField)
tempval.focus()
tempval.select()
if (document.all&&copytoclip==1){alert('all');
therange=tempval.createTextRange()
therange.execCommand("Copy")
window.status="Contents highlighted and copied to clipboard!"
setTimeout("window.status=''",1800)
}
}

//****************************Menu Left*************************************//
function change_menu(elem,action){
	document.getElementById(elem).src='images/'+elem+'-'+action+'.gif';
}//end function 
//********************************************************************//
function show_prod(id,count,lang){

	var i=0;
var limit=count;
for(i=0;i<limit;i++){
//	var diV='prod_details_'+i;
	var diVrequired='prod_details_'+id;
	//var menu=document.getElementById(diV);
		if(i==id){
			var menu_required=document.getElementById(diVrequired);
			if(menu_required.style.display=='none'){
				
				document.getElementById('prod_details_'+id).style.display='block';
				document.getElementById('category_'+id).className='category_active';
				document.getElementById('arrow_'+id).src='images/arrow_active.gif';
			} 
			else{
				
				document.getElementById('prod_details_'+i).style.display='none';
				document.getElementById('category_'+i).className='category';
				document.getElementById('arrow_'+i).src='images/arrow_'+lang+'.gif';
			}
			
		}
		else{
			
			document.getElementById('prod_details_'+i).style.display='none';
			document.getElementById('category_'+i).className='category';
			document.getElementById('arrow_'+i).src='images/arrow_'+lang+'.gif';
		}
}

}//end function 
//**************************************************************************//
function changeBack(id,count){
		var i=0;
var limit=count;
/*for(i=0;i<limit;i++){
	var diVrequired='prod_details_'+id;
	if(i==id){
			var menu_required=document.getElementById(diVrequired);
			
				
				
				menu_required.className='category_active';
				
			
				
				
				
			
			
		}
		else{
			
			
			document.getElementById('category_'+i).className='category';
			document.getElementById('arrow_'+i).src='images/arrow.gif';
		}
}*/
	
}//end function 
//********************************************************************//
function change_bg(id){
	//alert(id);
	document.getElementById('news_home_'+id).style.backgorund='#FFFCD4';
}//end function 
//******************************* End Menu ****************************************//
//---------------Search Alphabitical
function LoadModule(module,submodule,location,params,form)
	{ 
	
		var url="LoadModule.php";
		var now = new Date();
	//	var exitTime = now.getTime();
		var data="module="+module+"&submodule="+submodule;//+"&someParameter="+exitTime;
					//data+="&"+document.getElementById(form).serialize();//();

		if(params)
			data+="&"+params;
		if(form)
			data+="&"+$('#'+form).serialize();
		//	alert(data);
	//alert(module);
		if(!location)
			 location='working-area';
			// alert(location);
			//alert($(location).style.height);
document.getElementById(location).innerHTML="<table border='0' width='100%' height='100%' align='center' ><tr valign='middle'><td height='100%' align='center' valign='middle'><img valign='middle' src='images/working.gif'></td></tr></table>";	
			//alert(locationss);
  	
	 $.ajax({
   type: "POST",
   url: url,
   dataType: "html",
   data: data,
   success: function(html){
	   if(submodule=='insertleftVoting')
	   {
  		    var arr=html.split("~");
			showVoteResults(arr[0],arr[1]);
			document.getElementById(location).innerHTML='';
			
	   } else
	   if(submodule=='print_reserv')
	   {
			my_window= window.open ("","mywindow1","status=1");
			my_window.document.write(html);
			my_window.document.close();
			my_window.print();
	   } 
	   else 
	   {
		 // alert(html); 
			document.getElementById(location).innerHTML='';
			//alert('location'+location+'html'+html);
			$("#"+location).append(html);
			
					
			   if(module=='Article' && submodule=='articleHome')					
			   {
					var targetOffset = $('#'+location).offset().top;
					if($.browser.opera){
						$('html').animate({scrollTop: targetOffset}, 100);
					}else{
				  		$('html,body').animate({scrollTop: targetOffset}, 100);
					}			
			   }
			
		//document.getElementById(location).innerHTML= html;
	   }
   }
 });


	}
	//-------------ChangeLang
ChangeLang=function(epars)
{
		var now = new Date();
		var exitTime = now.getTime();

		
		var pars = 'someParameter='+exitTime+"&"+epars;
		//alert(pars);
		//var url="admin-page.php";
		var url="changeLang.php";
		var place="";
   

		
	
		 $.ajax({
   type: "POST",
   url: url,
   data: pars,
   success: function(html){
    // alert( "Data Saved: " + msg );
	//$("#working-area").append(html);
 eval(html);
   }
 });
	}
//-------------logout
loginNow=function(epars)
{
		var now = new Date();
		var exitTime = now.getTime();

		
		var pars = 'someParameter='+exitTime+"&"+epars;
		//alert(pars);
		//var url="admin-page.php";
		var url="loginto.php";
		var place="";
      


	 $.ajax({
   type: "POST",
   url: url,
   data: data,
   success: function(html){
    // alert( "Data Saved: " + msg );
	//$("#working-area").append(html);
 eval(html);
   }
 });
	}
///////////////  print -----------	
	function print_art(id,num){
	var v=id;	
	
  new_window= window.open ("","mywindow1","titlebar,resizeable,toolbar,scrollbars,menubar,status,innerwidth=800,innerheight=600");									  new_window.document.write("<link href='css/style.css' rel='artic_det' type='text/css'>");
//new_window.document.write("<link href='css/lightbox.css' rel='stylesheet' type='text/css'>");
	
		var T=document.getElementById(id).innerHTML;
		new_window.document.write(T);
	
	new_window.document.write("<br /><br /><div style='float:left; margin-left:150px; font-family:tahoma; font-weight:bold; color:#000000;'><a href='http://www.tawgeeh.com'>www.tawgeeh.com</a>   ÌãíÚ ÍÞæÞ ÇáØÈÚ ãÍÝæÙå áãæÞÚ  </div>");
	new_window.print();
  new_window.document.close();		
	
}


 function hlightWord(wordsToHighLight,data,id){

	var object=document.getElementById(id); 
	if(wordsToHighLight==""){
		 object.innerHTML=data;
	}
 	else 	
	{
		var arr=wordsToHighLight.split("+");
		
		var patternToMatch = new RegExp();
		for(var i=0;i<arr.length;i++){
			if(arr[i]!=""){
			patternToMatch.compile(arr[i],"gi");
  		var data=data.replace(patternToMatch,"--"+i);
			}
		}
		for(var i=0;i<arr.length;i++){
			patternToMatch.compile("--"+i,"gi");
  		var data=data.replace(patternToMatch,"<span style='" + "padding: 0px; background-color:#FF00FF" + "'>"+ arr[i] + "</span>");
		}
		object.innerHTML=data;
  }
}

	
// ------------ Change Country
ChangeCountry=function(form)
{
		var now = new Date();
		var exitTime = now.getTime();

		
		var pars = 'someParameter='+exitTime;
		if(form)
			pars+="&"+$('#'+form).serialize();
		
		//alert(pars);
		//var url="admin-page.php";
		var url="changeCountry.php";
		var place="";
	 $.ajax({
   type: "POST",
   url: url,
   data: pars,
   success: function(html){
    // alert( "Data Saved: " + msg );
	//$("#working-area").append(html);
	eval(html);
   }
 });

function showadmin(originalRequest)
	{
		
		
	eval(originalRequest.responseText);

	}
		
	function loginWaiting()
		{
		
		}
	}


//###############Voting################################
/************************************************************************************************************
Ajax poller
Copyright (C) 2006  DTHMLGoodies.com, Alf Magne Kalleland

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

Dhtmlgoodies.com., hereby disclaims all copyright interest in this script
written by Alf Magne Kalleland.

Alf Magne Kalleland, 2006
Owner of DHTMLgoodies.com
	
************************************************************************************************************/	




var serverSideFile = 'ajax-poller-cast-vote-php.php';
var voteLeftImage = 'images/graph_right_1.gif';
var voteRightImage = 'images/graph_left_1.gif';
var voteCenterImage = 'images/graph_middle_1.gif';

var graphMaxWidth = 130;	// It will actually be a little wider than this because of the rounded image at the left and right
var graphMinWidth = 20;	// Minimum size of graph
var pollScrollSpeed = 5;	// Lower = faster
var useCookiesToRememberCastedVotes = false;	// Use cookie to remember casted votes
var txt_totalVotes = 'مجموع الاصوات: ';

var ajaxObjects = new Array();
var pollVotes = new Array();
var pollVoteCounted = new Array();
var totalVotes = new Array();


/* Preload images */

var preloadedImages = new Array();
preloadedImages[0] = new Image();
preloadedImages[0].src = voteLeftImage;
preloadedImages[1] = new Image();
preloadedImages[1].src = voteRightImage;
preloadedImages[2] = new Image();
preloadedImages[2].src = voteCenterImage;

/*
These cookie functions are downloaded from 
http://www.mach5.com/support/analyzer/manual/html/General/CookiesJavaScript.htm
*/	
function Poller_Get_Cookie(name) { 
   var start = document.cookie.indexOf(name+"="); 
   var len = start+name.length+1; 
   if ((!start) && (name != document.cookie.substring(0,name.length))) return null; 
   if (start == -1) return null; 
   var end = document.cookie.indexOf(";",len); 
   if (end == -1) end = document.cookie.length; 
   return unescape(document.cookie.substring(len,end)); 
} 
// This function has been slightly modified
function Poller_Set_Cookie(name,value,expires,path,domain,secure) { 
	expires = expires * 60*60*24*1000;
	var today = new Date();
	var expires_date = new Date( today.getTime() + (expires) );
    var cookieString = name + "=" +escape(value) + 
       ( (expires) ? ";expires=" + expires_date.toGMTString() : "") + 
       ( (path) ? ";path=" + path : "") + 
       ( (domain) ? ";domain=" + domain : "") + 
       ( (secure) ? ";secure" : ""); 
    document.cookie = cookieString; 
}

	
function showVoteResults(pollId,result)
{
	//alert('poller_waitMessage' + pollId);
	document.getElementById('poller_waitMessage' + pollId).style.display='none';
	
	var xml = result;
	xml = xml.replace(/\n/gi,'');
	
	var reg = new RegExp("^.*?<pollerTitle_ar>(.*?)<.*$","gi");
	var pollerTitle_ar= xml.replace(reg,'$1');
	
	var resultDiv = document.getElementById('poller_results' + pollId);
	
	var titleP = document.createElement('P');
	titleP.className='result_pollerTitle';
	titleP.innerHTML = pollerTitle_ar;
	resultDiv.appendChild(titleP);	
	
	var options = xml.split(/<option>/gi);
	
	pollVotes[pollId] = new Array();
	totalVotes[pollId] = 0;
	for(var no=1;no<options.length;no++){
		
		var elements = options[no].split(/</gi);
		var currentOptionId = false;
		for(var no2=0;no2<elements.length;no2++){
			if(elements[no2].substring(0,1)!='/'){
				var key = elements[no2].replace(/^(.*?)>.*$/gi,'$1');
				var value = elements[no2].replace(/^.*?>(.*)$/gi,'$1');
			
				if(key.indexOf('optionText')>=0){
					var pOption = document.createElement('P');
					pOption.className='result_pollerOption';
					pOption.innerHTML = value;
					resultDiv.appendChild(pOption);					
					
				}
				
				if(key.indexOf('optionId')>=0){
					currentOptionId = value/1;
				}
				
				if(key.indexOf('votes')>=0){
					var voteDiv = document.createElement('DIV');
					voteDiv.className='result_pollGraph';
					resultDiv.appendChild(voteDiv);	
					
					var leftImage = document.createElement('IMG');
					leftImage.src = voteLeftImage;
					voteDiv.appendChild(leftImage);
					
					
					var numberDiv = document.createElement('DIV');
					numberDiv.style.backgroundImage = 'url(\'' + voteCenterImage + '\')';
					numberDiv.innerHTML = '0%';
					numberDiv.id = 'result_voteTxt' + currentOptionId;
					voteDiv.appendChild(numberDiv);	
					
					var rightImage = document.createElement('IMG');
					rightImage.src = voteRightImage;
					voteDiv.appendChild(rightImage);						
					
					pollVotes[pollId][currentOptionId] = value;					
					totalVotes[pollId] = totalVotes[pollId]/1 + value/1;
				}
			}
		}
	}
	
	var totalVoteP = document.createElement('P');
	totalVoteP.className = 'result_totalVotes';
	totalVoteP.innerHTML = txt_totalVotes + totalVotes[pollId];
	voteDiv.appendChild(totalVoteP);	
	
	setPercentageVotes(pollId);
	slideVotes(pollId,0);
}

function setPercentageVotes(pollId)
{
	for(var prop in pollVotes[pollId]){
		pollVotes[pollId][prop] =  Math.round( (pollVotes[pollId][prop] / totalVotes[pollId]) * 100);				
	}	
	
	var currentSum = 0;
	for(var prop in pollVotes[pollId]){
		currentSum = currentSum + pollVotes[pollId][prop]/1;			
	}
	pollVotes[pollId][prop] = pollVotes[pollId][prop] + (100-currentSum);
	
	
}

function slideVotes(pollId,currentPercent)
{
	currentPercent = currentPercent/1 + 1;
	
	for(var prop in pollVotes[pollId]){
		if(pollVotes[pollId][prop]>=currentPercent){
			var obj = document.getElementById('result_voteTxt' + prop);
			obj.innerHTML = currentPercent + '%';
			obj.style.width = Math.max(graphMinWidth,Math.round(currentPercent/100*graphMaxWidth)) + 'px';
		}			
	}
	
	if(currentPercent<100)setTimeout('slideVotes("' + pollId + '","' + currentPercent + '")',pollScrollSpeed);
}


function prepareForPollResults(pollId)
{
	document.getElementById('poller_waitMessage' + pollId).style.display='block';alert('dsfsf');
	document.getElementById('poller_question' + pollId).style.display='none';	
}


/*function castMyVote(pollId,formObj)
{	
	var elements = formObj.elements['vote[' + pollId + ']'];
	var optionId = false;
	for(var no=0;no<elements.length;no++){
		if(elements[no].checked)optionId = elements[no].value;
	}
	Poller_Set_Cookie('dhtmlgoodies_poller_' + pollId,'1',6000000);
	if(optionId){
	
		var ajaxIndex = ajaxObjects.length;
		ajaxObjects[ajaxIndex] = new sack();
		ajaxObjects[ajaxIndex].requestFile = serverSideFile + '?pollId=' + pollId + '&optionId=' + optionId;
		prepareForPollResults(pollId);
		ajaxObjects[ajaxIndex].onCompletion = function(){ showVoteResults(pollId,ajaxIndex); };	// Specify function that will be executed after file has been found
		ajaxObjects[ajaxIndex].runAJAX();		// Execute AJAX function	

	}	
}	

function displayResultsWithoutVoting(pollId)
{
	var ajaxIndex = ajaxObjects.length;
	ajaxObjects[ajaxIndex] = new sack();
	ajaxObjects[ajaxIndex].requestFile = serverSideFile + '?pollId=' + pollId;
	prepareForPollResults(pollId);
	ajaxObjects[ajaxIndex].onCompletion = function(){ showVoteResults(pollId,ajaxIndex); };	// Specify function that will be executed after file has been found
	ajaxObjects[ajaxIndex].runAJAX();		// Execute AJAX function		
	
	
}
*/

//############################ End of LoadModule.js ##########################################*/
/*############################################ jquery.prettyGallery.js ##########################################*/
/* ------------------------------------------------------------------------
	Class: prettyGallery
	Use: Gallery plugin for jQuery
	Author: Stephane Caron (http://www.no-margin-for-errors.com)
	Version: 1.1
------------------------------------------------------------------------- */

jQuery.fn.prettyGallery = function(settings) {
	settings = jQuery.extend({
		itemsPerPage : 2,
		animationSpeed : 'normal', /* fast/normal/slow */
		navigation : 'top',  /* top/bottom/both */
		of_label: ' of ', /* The content in the page "1 of 2" */
		previous_title_label: 'Previous page', /* The title of the previous link */
		next_title_label: 'Next page', /* The title of the next link */
		previous_label: 'Previous', /* The content of the previous link */
		next_label: 'Next' /* The content of the next link */
	}, settings);
	return this.each(function(){
		// Global variables needed in multiple functions.	
		var currentPage = 1;
		var itemWidth = 0;
		var itemHeight = 0;
		var galleryWidth = 0;
		var pageCount = 0;
		var animated = false;
		var $gallery = $(this);
		
		var prettyGalleryPrevious = function(caller) {
			// Make sure not to double animate, and not animate of the button is disabled
			if(animated || $(caller).hasClass('disabled')) return;
			animated = true;

			$gallery.find('li:lt('+(currentPage * settings.itemsPerPage)+')').each(function(i){
				$(this).animate({'left': parseFloat($(this).css('left')) + (galleryWidth + itemMargin) }, settings.animationSpeed, function(){
					animated = false;
				});
			});

			$gallery.find('li:gt('+ ((currentPage * settings.itemsPerPage) - 1) +')').each(function(i){
				$(this).animate({'left': parseFloat($(this).css('left')) + (galleryWidth + itemMargin) }, settings.animationSpeed);
			});

			currentPage--;

			_displayPaging();
		};

		var prettyGalleryNext = function(caller) {
			// Make sure not to double animate, and not animate of the button is disabled
			if(animated || $(caller).hasClass('disabled')) return;
			animated = true;

			$gallery.find('li:lt('+(currentPage * settings.itemsPerPage)+')').each(function(i){
				$(this).animate({'left': parseFloat($(this).css('left')) - (galleryWidth + itemMargin) }, settings.animationSpeed, function(){
					animated = false;
				});
			});

			$gallery.find('li:gt('+ ((currentPage * settings.itemsPerPage) - 1) +')').each(function(i){
				$(this).animate({'left': parseFloat($(this).css('left')) - (galleryWidth + itemMargin) }, settings.animationSpeed);
			});

			currentPage++;

			_displayPaging();
		};

		var _formatGallery = function() {
			itemWidth = $gallery.find('li:first').width();
			itemMargin = parseFloat($gallery.find('li:first').css('margin-right')) + parseFloat($gallery.find('li:first').css('margin-left')) + parseFloat($gallery.find('li:first').css('padding-left')) + parseFloat($gallery.find('li:first').css('padding-right')) + parseFloat($gallery.find('li:first').css('border-left-width')) + parseFloat($gallery.find('li:first').css('border-right-width'));
			itemHeight = $gallery.find('li:first').height() + parseFloat($gallery.find('li:first').css('margin-top')) + parseFloat($gallery.find('li:first').css('margin-bottom')) + parseFloat($gallery.find('li:first').css('padding-top')) + parseFloat($gallery.find('li:first').css('padding-bottom'));
			galleryWidth = (itemWidth + itemMargin) * settings.itemsPerPage - parseFloat($gallery.find('li:first').css('margin-right')); // We don't want the margin of the last item, that's why we remove it.

			$gallery.css({
				'width': galleryWidth,
				'height': itemHeight,
				'overflow': 'hidden',
				'position': 'relative',
				'clear': 'left'
			});
			$gallery.find('li').each(function(i){
				$(this).css({
					'position':'absolute',
					'top':0,
					'left':i * (itemWidth + itemMargin)
				});
			});

			$gallery.wrap('<div class="prettyGallery"></div>').addClass('prettyGallery');
		};

		var _displayPaging = function() {
			$cg = $gallery.parents('div.prettyGallery:first'); // The containing gallery

			$cg.find('ul.prettyNavigation span.current').text(currentPage);
			$cg.find('ul.prettyNavigation span.total').text(pageCount);

			// Make sur all the links are enabled
			$cg.find('ul.prettyNavigation li a').removeClass('disabled');

			// Display the proper nav
			if(currentPage == 1){
				// Hide the previous button
				$cg.find('ul.prettyNavigation li.prev a').addClass('disabled');
			} else if(currentPage == pageCount) {
				// Hide the next button
				$cg.find('ul.prettyNavigation li.next a').addClass('disabled');
			};
		};

		var _applyNav = function() {
			var template = '';
			template +='<ul class="prettyNavigation">';
			template += '<li class="prev"><a href="#" title="'+settings.previous_title_label+'">'+settings.previous_label+'</a></li>';
			template += '<li><span class="current">1</span>'+settings.of_label+'<span class="total">1</span></li>';
			template += '<li class="next"><a href="#" title="'+settings.next_title_label+'">'+settings.next_label+'</a></li>';
			template += '</ul>';

			switch(settings.navigation){
				case 'top':
					$gallery.before(template);
					break;
				case 'bottom':
					$gallery.after(template);
					break;
				case 'both':
					$gallery.before(template);
					$gallery.after(template);
					break;
			};

			// Adjust the nav to the gallery width
			$theNav = $gallery.parent('div.prettyGallery:first').find('ul.prettyNavigation');
			galleryBorderWidth = parseFloat($theNav.css('border-left-width')) + parseFloat($theNav.css('border-right-width'));
			$theNav.width(galleryWidth - galleryBorderWidth);
			$theNav.each(function(){
				$(this).find('li:eq(1)').width(galleryWidth - galleryBorderWidth - parseFloat($(this).parent().find('ul.prettyNavigation li:first').width()) - parseFloat($(this).parent().find('ul.prettyNavigation li:last').width()));
			});

			// Apply the functions to the buttons
			$theNav.find('li.prev a').bind('click',function(){
				prettyGalleryPrevious(this);
				return false;
			});

			$theNav.find('li.next a').bind('click',function(){
				prettyGalleryNext(this);
				return false;
			});
		};
		
		// Check if we need the gallery
		if($(this).find('li').size() > settings.itemsPerPage) {		
			// Set the number of pages
			pageCount = Math.ceil($(this).find('li').size() / settings.itemsPerPage);
			
			// Format the gallery properly
			_formatGallery();
			
			// Build and display the nav
			_applyNav();
			
			// Display the proper paging
			_displayPaging(this);
			currentPage = 1;
		};
	});};
/*############################################ End of jquery.prettyGallery.js ##########################################*/
/*############################################ jquery.prettyPhoto.js ##########################################*/
/* ------------------------------------------------------------------------
	Class: prettyPhoto
	Use: Lightbox clone for jQuery
	Author: Stephane Caron (http://www.no-margin-for-errors.com)
	Version: 2.2.2
------------------------------------------------------------------------- */

	$.fn.prettyPhoto = function(settings) {
		// global Variables
		var isSet = false; /* Total position in the array */
		var setCount = 0; /* Total images in the set */
		var setPosition = 0; /* Position in the set */
		var arrayPosition = 0; /* Total position in the array */
		var hasTitle = false;
		var caller = 0;
		var doresize = true;
		var imagesArray = [];
	
		$(window).scroll(function(){ _centerPicture(); });
		$(window).resize(function(){ _centerPicture(); _resizeOverlay(); });
		$(document).keyup(function(e){
			switch(e.keyCode){
				case 37:
					if (setPosition == 1) return;
					changePicture('previous');
					break;
				case 39:
					if (setPosition == setCount) return;
					changePicture('next');
					break;
				case 27:
					close();
					break;
			};
	    });
 
	
		settings = jQuery.extend({
			animationSpeed: 'normal', /* fast/slow/normal */
			padding: 40, /* padding for each side of the picture */
			opacity: 0.35, /* Value betwee 0 and 1 */
			showTitle: true, /* true/false */
			allowresize: true, /* true/false */
			counter_separator_label: '/' /* Teh separator for the gallery counter 1 "of" 2 */
		}, settings);
	
		$(this).each(function(){
			imagesArray[imagesArray.length] = this;
			$(this).bind('click',function(){
				open(this); return false;
			});
		});
	
		function open(el) {
			caller = $(el);
		
			// Find out if the picture is part of a set
			theRel = $(caller).attr('rel');
			galleryRegExp = /\[(?:.*)\]/;
			theGallery = galleryRegExp.exec(theRel);
		
			// Find out the type of content
			contentType = "image";
			if($(caller).attr('href').indexOf('.swf') > 0){ hasTitle = false; contentType = 'flash'; };
		
			// Calculate the number of items in the set, and the position of the clicked picture.
			isSet = false;
			setCount = 0;
			for (i = 0; i < imagesArray.length; i++){
				if($(imagesArray[i]).attr('rel').indexOf(theGallery) != -1){
					setCount++;
					if(setCount > 1) isSet = true;

					if($(imagesArray[i]).attr('href') == $(el).attr('href')){
						setPosition = setCount;
						arrayPosition = i;
					};
				};
			};
		
			_buildOverlay(isSet);

			// Display the current position
			$('div.pictureHolder p.currentTextHolder').text(setPosition + settings.counter_separator_label + setCount);

			// Position the picture in the center of the viewing area
			_centerPicture();
		
			$('div.pictureHolder #fullResImageContainer').hide();
			$('.loaderIcon').show();

			// Display the correct type of information
			(contentType == 'image') ? _preload() : _writeFlash();
		};
	
		showimage = function(width,height,containerWidth,containerHeight,contentHeight,contentWidth,resized){
			$('.loaderIcon').hide();
			var scrollPos = _getScroll();

			if($.browser.opera) {
				windowHeight = window.innerHeight;
				windowWidth = window.innerWidth;
			}else{
				windowHeight = $(window).height();
				windowWidth = $(window).width();
			};

			$('div.pictureHolder .content').animate({'height':contentHeight,'width':containerWidth},settings.animationSpeed);

			projectedTop = scrollPos['scrollTop'] + ((windowHeight/2) - (containerHeight/2));
			if(projectedTop < 0) projectedTop = 0 + $('div.prettyPhotoTitle').height();

			// Resize the holder
			$('div.pictureHolder').animate({
				'top': projectedTop,
				'left': ((windowWidth/2) - (containerWidth/2)),
				'width': containerWidth
			},settings.animationSpeed,function(){
				$('#fullResImage').attr({
					'width':width,
					'height':height
				});

				$('div.pictureHolder').width(containerWidth);
				$('div.pictureHolder .hoverContainer').height(height).width(width);

				// Show the nav elements
				_shownav();

				// Fade the new image
				$('div.pictureHolder #fullResImageContainer').fadeIn(settings.animationSpeed);
			
				// Fade the resizing link if the image is resized
				if(resized) $('a.expand,a.contract').fadeIn(settings.animationSpeed);
			});
		};
	
		function changePicture(direction){
			if(direction == 'previous') {
				arrayPosition--;
				setPosition--;
			}else{
				arrayPosition++;
				setPosition++;
			};

			// Allow the resizing of the images
			if(!doresize) doresize = true;

			// Fade out the current picture
			$('div.pictureHolder .hoverContainer,div.pictureHolder .details').fadeOut(settings.animationSpeed);
			$('div.pictureHolder #fullResImageContainer').fadeOut(settings.animationSpeed,function(){
				$('.loaderIcon').show();
			
				// Preload the image
				_preload();
			});

			_hideTitle();
			$('a.expand,a.contract').fadeOut(settings.animationSpeed,function(){
				$(this).removeClass('contract').addClass('expand');
			});
		};
	
		function close(){
			$('div.pictureHolder,div.prettyPhotoTitle').fadeOut(settings.animationSpeed, function(){
				$('div.prettyPhotoOverlay').fadeOut(settings.animationSpeed, function(){
					$('div.prettyPhotoOverlay,div.pictureHolder,div.prettyPhotoTitle').remove();
				
					// To fix the bug with IE select boxes
					if($.browser.msie && $.browser.version == 6){
						$('select').css('visibility','visible');
					};
				});
			});
		};
	
		function _checkPosition(){
			// If at the end, hide the next link
			if(setPosition == setCount) {
				$('div.pictureHolder a.next').css('visibility','hidden');
				$('div.pictureHolder a.arrow_next').addClass('disabled').unbind('click');
			}else{ 
				$('div.pictureHolder a.next').css('visibility','visible');
				$('div.pictureHolder a.arrow_next.disabled').removeClass('disabled').bind('click',function(){
					changePicture('next');
					return false;
				});
			};
		
			// If at the beginning, hide the previous link
			if(setPosition == 1) {
				$('div.pictureHolder a.previous').css('visibility','hidden');
				$('div.pictureHolder a.arrow_previous').addClass('disabled').unbind('click');
			}else{
				$('div.pictureHolder a.previous').css('visibility','visible');
				$('div.pictureHolder a.arrow_previous.disabled').removeClass('disabled').bind('click',function(){
					changePicture('previous');
					return false;
				});
			};
		
			// Change the current picture text
			$('div.pictureHolder p.currentTextHolder').text(setPosition + settings.counter_separator_label + setCount);
		
			(isSet) ? $c = $(imagesArray[arrayPosition]) : $c = $(caller);

			if($c.attr('title')){
				$('div.pictureHolder .description').show().html(unescape($c.attr('title')));
			}else{
				$('div.pictureHolder .description').hide().text('');
			};
		
			if($c.find('img').attr('alt') && settings.showTitle){
				hasTitle = true;
				$('div.prettyPhotoTitle .prettyPhotoTitleContent').html(unescape($c.find('img').attr('alt')));
			}else{
				hasTitle = false;
			};
		};
	
		function _fitToViewport(width,height){
			hasBeenResized = false;
		
			$('div.pictureHolder .details').width(width); /* To have the correct height */
			$('div.pictureHolder .details p.description').width(width - parseFloat($('div.pictureHolder a.close').css('width'))); /* So it doesn't overlap the button */
		
			// Get the container size, to resize the holder to the right dimensions
			contentHeight = height + parseFloat($('div.pictureHolder .details').height()) + parseFloat($('div.pictureHolder .details').css('margin-top')) + parseFloat($('div.pictureHolder .details').css('margin-bottom'));
			contentWidth = width;
			containerHeight = height + parseFloat($('div.prettyPhotoTitle').height()) + parseFloat($('div.pictureHolder .top').height()) + parseFloat($('div.pictureHolder .bottom').height());
			containerWidth = width + settings.padding;
		
			// Define them in case there's no resize needed
			imageWidth = width;
			imageHeight = height;

			if($.browser.opera) {
				windowHeight = window.innerHeight;
				windowWidth = window.innerWidth;
			}else{
				windowHeight = $(window).height();
				windowWidth = $(window).width();
			};
		
			if( ((containerWidth > windowWidth) || (containerHeight > windowHeight)) && doresize && settings.allowresize) {
				hasBeenResized = true;
			
				if((containerWidth > windowWidth) && (containerHeight > windowHeight)){
					// Get the original geometry and calculate scales
					var xscale =  (containerWidth + 200) / windowWidth;
					var yscale = (containerHeight + 200) / windowHeight;
				}else{
					// Get the original geometry and calculate scales
					var xscale = windowWidth / containerWidth;
					var yscale = windowHeight / containerHeight;
				}

				// Recalculate new size with default ratio
				if (yscale>xscale){
					imageWidth = Math.round(width * (1/yscale));
					imageHeight = Math.round(height * (1/yscale));
				} else {
					imageWidth = Math.round(width * (1/xscale));
					imageHeight = Math.round(height * (1/xscale));
				};
			
				// Define the new dimensions
				contentHeight = imageHeight + parseFloat($('div.pictureHolder .details').height()) + parseFloat($('div.pictureHolder .details').css('margin-top')) + parseFloat($('div.pictureHolder .details').css('margin-bottom'));
				contentWidth = imageWidth;
				containerHeight = imageHeight + parseFloat($('div.prettyPhotoTitle').height()) + parseFloat($('div.pictureHolder .top').height()) + parseFloat($('div.pictureHolder .bottom').height());
				containerWidth = imageWidth + settings.padding;
			
				$('div.pictureHolder .details').width(contentWidth); /* To have the correct height */
				$('div.pictureHolder .details p.description').width(contentWidth - parseFloat($('div.pictureHolder a.close').css('width'))); /* So it doesn't overlap the button */
			};

			return {
				width:imageWidth,
				height:imageHeight,
				containerHeight:containerHeight,
				containerWidth:containerWidth,
				contentHeight:contentHeight,
				contentWidth:contentWidth,
				resized:hasBeenResized
			};
		};
	
		function _centerPicture(){
			//Make sure the gallery is open
			if($('div.pictureHolder').size() > 0){
			
				var scrollPos = _getScroll();
			
				if($.browser.opera) {
					windowHeight = window.innerHeight;
					windowWidth = window.innerWidth;
				}else{
					windowHeight = $(window).height();
					windowWidth = $(window).width();
				};
			
				if(doresize) {
					projectedTop = (windowHeight/2) + scrollPos['scrollTop'] - ($('div.pictureHolder').height()/2);
					if(projectedTop < 0) projectedTop = 0 + $('div.prettyPhotoTitle').height();
					
					$('div.pictureHolder').css({
						'top': projectedTop,
						'left': (windowWidth/2) + scrollPos['scrollLeft'] - ($('div.pictureHolder').width()/2)
					});
			
					$('div.prettyPhotoTitle').css({
						'top' : $('div.pictureHolder').offset().top - $('div.prettyPhotoTitle').height(),
						'left' : $('div.pictureHolder').offset().left + (settings.padding/2)
					});
				};
			};
		};
	
		function _shownav(){
			if(isSet) $('div.pictureHolder .hoverContainer').fadeIn(settings.animationSpeed);
			$('div.pictureHolder .details').fadeIn(settings.animationSpeed);

			_showTitle();
		};
	
		function _showTitle(){
			if(settings.showTitle && hasTitle){
				$('div.prettyPhotoTitle').css({
					'top' : $('div.pictureHolder').offset().top,
					'left' : $('div.pictureHolder').offset().left + (settings.padding/2),
					'display' : 'block'
				});
			
				$('div.prettyPhotoTitle div.prettyPhotoTitleContent').css('width','auto');
			
				if($('div.prettyPhotoTitle').width() > $('div.pictureHolder').width()){
					$('div.prettyPhotoTitle div.prettyPhotoTitleContent').css('width',$('div.pictureHolder').width() - (settings.padding * 2));
				}else{
					$('div.prettyPhotoTitle div.prettyPhotoTitleContent').css('width','');
				};
			
				$('div.prettyPhotoTitle').animate({'top':($('div.pictureHolder').offset().top - 22)},settings.animationSpeed);
			};
		};
	
		function _hideTitle() {
			$('div.prettyPhotoTitle').animate({'top':($('div.pictureHolder').offset().top)},settings.animationSpeed,function() { $(this).css('display','none'); });
		};
	
		function _preload(){
			// Hide the next/previous links if on first or last images.
			_checkPosition();
		
			// Set the new image
			imgPreloader = new Image();
		
			// Preload the neighbour images
			nextImage = new Image();
			if(isSet) nextImage.src = $(imagesArray[arrayPosition + 1]).attr('href');
			prevImage = new Image();
			if(isSet && imagesArray[arrayPosition - 1]) prevImage.src = $(imagesArray[arrayPosition - 1]).attr('href');

			$('div.pictureHolder .content').css('overflow','hidden');
		
			if(isSet) {
				$('div.pictureHolder #fullResImage').attr('src',$(imagesArray[arrayPosition]).attr('href'));
			}else{
				$('div.pictureHolder #fullResImage').attr('src',$(caller).attr('href'));
			};

			imgPreloader.onload = function(){
				var correctSizes = _fitToViewport(imgPreloader.width,imgPreloader.height);
				imgPreloader.width = correctSizes['width'];
				imgPreloader.height = correctSizes['height'];
			
				// Need that small delay for the anim to be nice
				setTimeout('showimage(imgPreloader.width,imgPreloader.height,'+correctSizes["containerWidth"]+','+correctSizes["containerHeight"]+','+correctSizes["contentHeight"]+','+correctSizes["contentWidth"]+','+correctSizes["resized"]+')',500);
			};
		
			(isSet) ? imgPreloader.src = $(imagesArray[arrayPosition]).attr('href') : imgPreloader.src = $(caller).attr('href');
		};
	
		function _getScroll(){
			scrollTop = window.pageYOffset || document.documentElement.scrollTop || 0;
			scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || 0;
			return {scrollTop:scrollTop,scrollLeft:scrollLeft};
		};
	
		function _resizeOverlay() {
			$('div.prettyPhotoOverlay').css({
				'height':$(document).height(),
				'width':$(window).width()
			});
		};
	
		function _writeFlash(){
			flashParams = $(caller).attr('rel').split(';');
			$(flashParams).each(function(i){
				// Define the width and height
				if(flashParams[i].indexOf('width') >= 0) flashWidth = flashParams[i].substring(flashParams[i].indexOf('width') + 6, flashParams[i].length);
				if(flashParams[i].indexOf('height') >= 0) flashHeight = flashParams[i].substring(flashParams[i].indexOf('height') + 7, flashParams[i].length);
				if(flashParams[i].indexOf('flashvars') >= 0) flashVars = flashParams[i].substring(flashParams[i].indexOf('flashvars') + 10, flashParams[i].length);
			});
		
			$('.pictureHolder #fullResImageContainer').append('<embed width="'+flashWidth+'" height="'+flashHeight+'" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" wmode="opaque" name="prettyFlash" flashvars="'+flashVars+'" allowscriptaccess="always" bgcolor="#FFFFFF" quality="high" src="'+$(caller).attr('href')+'"/>');
			$('#fullResImage').hide();
		
			contentHeight = parseFloat(flashHeight) + parseFloat($('div.pictureHolder .details').height()) + parseFloat($('div.pictureHolder .details').css('margin-top')) + parseFloat($('div.pictureHolder .details').css('margin-bottom'));
			contentWidth = parseFloat(flashWidth)+ parseFloat($('div.pictureHolder .details').width()) + parseFloat($('div.pictureHolder .details').css('margin-left')) + parseFloat($('div.pictureHolder .details').css('margin-right'));
			containerHeight = contentHeight + parseFloat($('div.pictureHolder .top').height()) + parseFloat($('div.pictureHolder .bottom').height());
			containerWidth = parseFloat(flashWidth) + parseFloat($('div.pictureHolder .content').css("padding-left")) + parseFloat($('div.pictureHolder .content').css("padding-right")) + settings.padding;
		
			setTimeout('showimage('+flashWidth+','+flashHeight+','+containerWidth+','+containerHeight+','+contentHeight+','+contentWidth+')',500);
		};
	
		function _buildOverlay(){
		
			// Build the background overlay div
			backgroundDiv = "<div class='prettyPhotoOverlay'></div>";
			$('body').append(backgroundDiv);
			$('div.prettyPhotoOverlay').css('height',$(document).height()).bind('click',function(){
				close();
			});
		
			// Basic HTML for the picture holder
			pictureHolder = '<div class="pictureHolder"><div class="top"><div class="left"></div><div class="middle"></div><div class="right"></div></div><div class="content"><a href="#" class="expand" title="Expand the image">Expand</a><div class="loaderIcon"></div><div class="hoverContainer"><a class="next" href="#">next</a><a class="previous" href="#">previous</a></div><div id="fullResImageContainer"><img id="fullResImage" src="" /></div><div class="details clearfix"><a class="close" href="#">Close</a><p class="description"></p><div class="nav"><a href="#" class="arrow_previous">Previous</a><p class="currentTextHolder">0'+settings.counter_separator_label+'0</p><a href="#" class="arrow_next">Next</a></div></div></div><div class="bottom"><div class="left"></div><div class="middle"></div><div class="right"></div></div></div>';
		
			// Basic html for the title holder
			titleHolder = '<div class="prettyPhotoTitle"><div class="prettyPhotoTitleLeft"></div><div class="prettyPhotoTitleContent"></div><div class="prettyPhotoTitleRight"></div></div>';

			$('body').append(pictureHolder).append(titleHolder);

			$('.pictureHolder,.titleHolder').css({'opacity': 0});
			$('a.close').bind('click',function(){ close(); return false; });
			$('a.expand').bind('click',function(){
			
				// Expand the image
				if($(this).hasClass('expand')){
					$(this).removeClass('expand').addClass('contract');
					doresize = false;
				}else{
					$(this).removeClass('contract').addClass('expand');
					doresize = true;
				};
			
				_hideTitle();
				$('div.pictureHolder .hoverContainer,div.pictureHolder #fullResImageContainer').fadeOut(settings.animationSpeed);
				$('div.pictureHolder .details').fadeOut(settings.animationSpeed,function(){
					_preload();
				});
			
				return false;
			});
		
			$('.pictureHolder .previous,.pictureHolder .arrow_previous').bind('click',function(){
				changePicture('previous');
				return false;
			});
		
			$('.pictureHolder .next,.pictureHolder .arrow_next').bind('click',function(){
				changePicture('next');
				return false;
			});

			$('.hoverContainer').css({
				'margin-left': settings.padding/2
			});
		
			// If it's not a set, hide the links
			if(!isSet) {
				$('.hoverContainer,.nav').hide();
			};


			// To fix the bug with IE select boxes
			if($.browser.msie && $.browser.version == 6){
				$('select').css('visibility','hidden');
			};

			// Then fade it in
			$('div.prettyPhotoOverlay').css('opacity',0).fadeTo(settings.animationSpeed,settings.opacity, function(){
				$('div.pictureHolder').css('opacity',0).fadeIn(settings.animationSpeed,function(){
					// To fix an IE bug
					$('div.pictureHolder').attr('style','left:'+$('div.pictureHolder').css('left')+';top:'+$('div.pictureHolder').css('top')+';');
				});
			});
		};
	};
/*############################################ End of jquery.prettyPhoto.js ##########################################*/
/*############################################ thickbox.js ##########################################*/
/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
		  
var tb_pathToImage = "images/loadingAnimation.gif";

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call tb_init
$(document).ready(function(){   
	tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
});

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
	$(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	tb_show(t,a,g);
	this.blur();
	return false;
	});
}

function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link

	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}else{//all others
			if(document.getElementById("TB_overlay") === null){
				$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}
		
		if(tb_detectMacXFF()){
			$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$('#TB_load').show();//show loader
		
		var baseURL;
	   if(url.indexOf("?")!==-1){ //ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	   }else{ 
	   		baseURL = url;
	   }
	   
	   var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
	   var urlType = baseURL.toLowerCase().match(urlString);

		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
				
			TB_PrevCaption = "";
			TB_PrevURL = "";
			TB_PrevHTML = "";
			TB_NextCaption = "";
			TB_NextURL = "";
			TB_NextHTML = "";
			TB_imageCount = "";
			TB_FoundURL = false;
			if(imageGroup){
				TB_TempArray = $("a[@rel="+imageGroup+"]").get();
				for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
					var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
						if (!(TB_TempArray[TB_Counter].href == url)) {						
							if (TB_FoundURL) {
								TB_NextCaption = TB_TempArray[TB_Counter].title;
								TB_NextURL = TB_TempArray[TB_Counter].href;
								TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
							} else {
								TB_PrevCaption = TB_TempArray[TB_Counter].title;
								TB_PrevURL = TB_TempArray[TB_Counter].href;
								TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
							}
						} else {
							TB_FoundURL = true;
							TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = tb_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			$("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div>"); 		
			
			$("#TB_closeWindowButton").click(tb_remove);
			
			if (!(TB_PrevHTML === "")) {
				function goPrev(){
					if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
					return false;	
				}
				$("#TB_prev").click(goPrev);
			}
			
			if (!(TB_NextHTML === "")) {		
				function goNext(){
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_NextCaption, TB_NextURL, imageGroup);				
					return false;	
				}
				$("#TB_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TB_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TB_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			tb_position();
			$("#TB_load").remove();
			$("#TB_ImageOff").click(tb_remove);
			$("#TB_window").css({display:"block"}); //for safari using css instead of show
			};
			
			imgPreloader.src = url;
		}else{//code to show html
			
			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = tb_parseQuery( queryString );

			TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
			TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = TB_WIDTH - 30;
			ajaxContentH = TB_HEIGHT - 45;
			
			if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window		
					urlNoQuery = url.split('TB_');
					$("#TB_iframeContent").remove();
					if(params['modal'] != "true"){//iframe no modal
						$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					}else{//iframe modal
					$("#TB_overlay").unbind();
						$("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					}
			}else{// not an iframe, ajax
					if($("#TB_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
						$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a> or Esc Key</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
						}else{//ajax modal
						$("#TB_overlay").unbind();
						$("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");	
						}
					}else{//this means the window is already up, we are just loading new content via ajax
						$("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
						$("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
						$("#TB_ajaxContent")[0].scrollTop = 0;
						$("#TB_ajaxWindowTitle").html(caption);
					}
			}
					
			$("#TB_closeWindowButton").click(tb_remove);
			
				if(url.indexOf('TB_inline') != -1){	
					$("#TB_ajaxContent").append($('#' + params['inlineId']).children());
					$("#TB_window").unload(function () {
						$('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
					});
					tb_position();
					$("#TB_load").remove();
					$("#TB_window").css({display:"block"}); 
				}else if(url.indexOf('TB_iframe') != -1){
					tb_position();
					if($.browser.safari){//safari needs help because it will not fire iframe onload
						$("#TB_load").remove();
						$("#TB_window").css({display:"block"});
					}
				}else{
					$("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						tb_position();
						$("#TB_load").remove();
						tb_init("#TB_ajaxContent a.thickbox");
						$("#TB_window").css({display:"block"});
					});
				}
			
		}

		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				}	
			};
		}
		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function tb_showIframe(){
	$("#TB_load").remove();
	$("#TB_window").css({display:"block"});
}

function tb_remove() {
 	$("#TB_imageOff").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	$("#TB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function tb_position() {
$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}

function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function tb_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}

function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}
/*############################################ End of thickbox.js ##########################################*/
/*############################################ jquery.accessible-news-slider.js ##########################################*/
/*

	----------------------------------------------------------------------------------------------------
	Accessible News Slider
	----------------------------------------------------------------------------------------------------
	
	Author:
	Brian Reindel
	
	Author URL:
	http://blog.reindel.com

	License:
	Unrestricted. This script is free for both personal and commercial use.

*/

jQuery.fn.accessNews = function( settings,language ) {
	settings = jQuery.extend({
        headline : "Top Stories",
        speed : "normal",
		slideBy : 2,
		language : language
    }, settings);

    return this.each(function() {	
		jQuery.fn.accessNews.run( jQuery( this ), settings );
    });
};
jQuery.fn.accessNews.run = function( $this, settings ) {
	jQuery( ".javascript_css", $this ).css( "display", "none" );
	var ul = jQuery( "ul:eq(0)", $this );
	var li = ul.children();
	if ( li.length > settings.slideBy ) {
	var $next = jQuery( ".next > a", $this );
	var $back = jQuery( ".back > a", $this );
	if(settings.language!='en')
		$back.parent().after( [ "<p class=\"view_all\">", settings.headline, "", "  اجمالى الاخبار ", li.length,"</p>" ].join( "" ) );
	else
		$back.parent().after( [ "<p class=\"view_all\">", settings.headline, "", "  Total: ", li.length,"</p>" ].join( "" ) );	
	var liWidth = jQuery( li[0] ).width();
	var animating = false;
	ul.css( "width", ( li.length * liWidth ) );
	$next.click(function() {
		if ( !animating ) {
			animating = true;
			offsetLeft = parseInt( ul.css( "left" ) ) - ( liWidth * settings.slideBy );
			if ( offsetLeft + ul.width() > 0 ) {
				$back.css( "display", "block" );
				ul.animate({
					left: offsetLeft
				}, settings.speed, function() {
					if ( parseInt( ul.css( "left" ) ) + ul.width() <= liWidth * settings.slideBy ) {
						$next.css( "display", "none" );
					}
					animating = false;
				});
			} else {
				animating = false;
			}
		}
		return false;
	});
	$back.click(function() {
		if ( !animating ) {
			animating = true;
			offsetRight = parseInt( ul.css( "left" ) ) + ( liWidth * settings.slideBy );
			if ( offsetRight + ul.width() <= ul.width() ) {
				$next.css( "display", "block" );
				ul.animate({
					left: offsetRight
				}, settings.speed, function() {
					if ( parseInt( ul.css( "left" ) ) == 0 ) {
						$back.css( "display", "none" );
					}
					animating = false;
				});
			} else {
				animating = false;
			}
		}
		return false;
	});
	$next.css( "display", "block" );
	/*.parent().after( [ "<p class=\"view_all\">fgfg", settings.headline, " - ", li.length, " total ( <a href=\"#\">view all</a> )</p>" ].join( "" ) );	*/

	jQuery( ".view_all > a, .skip_to_news > a", $this ).click(function() {
		var skip_to_news = ( jQuery( this ).html() == "Skip to News" );
		if ( jQuery( this ).html() == "ÚÑÖ Çáßá" || skip_to_news ) {
			ul.css( "width", "auto" ).css( "left", "0" );
			$next.css( "display", "none" );
			$back.css( "display", "none" );
			if ( !skip_to_news ) {
				jQuery( this ).html( "ÚÑÖ ãÎÊÕÑ" );
			}
		} else {
			if ( !skip_to_news ) {
				jQuery( this ).html( "ÚÑÖ Çáßá" );
			}
			ul.css( "width", ( li.length * liWidth ) );
			$next.css( "display", "block" );
		}
		return false;
	});
	}
};
/*#################################### End of jquery.accessible-news-slider.js ########################################*/
/*#################################### jquery.cross-slide.js ########################################*/
/*
 * Copyright 2007-2009 by Tobia Conforto <tobia.conforto@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General
 * Public License as published by the Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program; if not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * Versions: 0.1    2007-08-19  Initial release
 *                  2008-08-21  Re-released under GPL v2
 *           0.1.1  2008-09-18  Compatibility with prototype.js
 *           0.2    2008-10-15  Linkable images, contributed by Tim Rainey <tim@zmlabs.com>
 *           0.3    2008-10-22  Added option to repeat the animation a number of times, then stop
 *           0.3.1  2008-11-11  Better error messages
 *           0.3.2  2008-11-11  Fixed a couple of CSS bugs, contributed by Erwin Bot <info@ixgcms.nl>
 *           0.3.3  2008-12-14  Added onclick option
 *           0.3.4  2009-03-12  Added shuffle option, contributed by Ralf Santbergen <ralf_santbergen@hotmail.com>
 *           0.3.5  2009-03-12  Fixed usage of href parameter in 'Ken Burns' mode
 */
<!-- Banner Slider  -->
jQuery.fn.crossSlide = function(opts, plan) {
	var self = this,
			self_width = this.width(),
			self_height = this.height();

	// generic utilities
	function format(str) {
		for (var i = 1; i < arguments.length; i++)
			str = str.replace(new RegExp('\\{' + (i-1) + '}', 'g'), arguments[i]);
		return str;
	}

	function abort() {
		arguments[0] = 'crossSlide: ' + arguments[0];
		throw format.apply(null, arguments);
	}

	// first preload all the images, while getting their actual width and height
	(function(proceed) {

		var n_loaded = 0;
		function loop(i, img) {
			// for (i = 0; i < plan.length; i++) but with independent var i, img (for the closures)
			img.onload = function(e) {
				n_loaded++;
				plan[i].width = img.width;
				plan[i].height = img.height;
				if (n_loaded == plan.length)
					proceed();
			}
			img.src = plan[i].src;
			if (i + 1 < plan.length)
				loop(i + 1, new Image());
		}
		loop(0, new Image());

	})(function() {  // then proceed

		// utility to parse "from" and "to" parameters
		function parse_position_param(param) {
			var zoom = 1;
			var tokens = param.replace(/^\s*|\s*$/g, '').split(/\s+/);
			if (tokens.length > 3) throw new Error();
			if (tokens[0] == 'center')
				if (tokens.length == 1)
					tokens = ['center', 'center'];
				else if (tokens.length == 2 && tokens[1].match(/^[\d.]+x$/i))
					tokens = ['center', 'center', tokens[1]];
			if (tokens.length == 3)
				zoom = parseFloat(tokens[2].match(/^([\d.]+)x$/i)[1]);
			var pos = tokens[0] + ' ' + tokens[1];
			if (pos == 'left top'      || pos == 'top left')      return { xrel:  0, yrel:  0, zoom: zoom };
			if (pos == 'left center'   || pos == 'center left')   return { xrel:  0, yrel: .5, zoom: zoom };
			if (pos == 'left bottom'   || pos == 'bottom left')   return { xrel:  0, yrel:  1, zoom: zoom };
			if (pos == 'center top'    || pos == 'top center')    return { xrel: .5, yrel:  0, zoom: zoom };
			if (pos == 'center center')                           return { xrel: .5, yrel: .5, zoom: zoom };
			if (pos == 'center bottom' || pos == 'bottom center') return { xrel: .5, yrel:  1, zoom: zoom };
			if (pos == 'right top'     || pos == 'top right')     return { xrel:  1, yrel:  0, zoom: zoom };
			if (pos == 'right center'  || pos == 'center right')  return { xrel:  1, yrel: .5, zoom: zoom };
			if (pos == 'right bottom'  || pos == 'bottom right')  return { xrel:  1, yrel:  1, zoom: zoom };
			return {
				xrel: parseInt(tokens[0].match(/^(\d+)%$/)[1]) / 100,
				yrel: parseInt(tokens[1].match(/^(\d+)%$/)[1]) / 100,
				zoom: zoom
			};
		}

		// utility to compute the css for a given phase between p.from and p.to
		// phase = 1: begin fade-in,  2: end fade-in,  3: begin fade-out,  4: end fade-out
		function position_to_css(p, phase) {
			switch (phase) {
				case 1:
					var pos = 0;
					break;
				case 2:
					var pos = fade_ms / (p.time_ms + 2 * fade_ms);
					break;
				case 3:
					var pos = 1 - fade_ms / (p.time_ms + 2 * fade_ms);
					break;
				case 4:
					var pos = 1;
					break;
			}
			return {
				left:   Math.round(p.from.left   + pos * (p.to.left   - p.from.left  )),
				top:    Math.round(p.from.top    + pos * (p.to.top    - p.from.top   )),
				width:  Math.round(p.from.width  + pos * (p.to.width  - p.from.width )),
				height: Math.round(p.from.height + pos * (p.to.height - p.from.height))
			};
		}

		// check global params
		if (! opts.fade)
			abort('missing fade parameter.');
		if (opts.speed && opts.sleep)
			abort('you cannot set both speed and sleep at the same time.');
		// conversion from sec to ms; from px/sec to px/ms
		var fade_ms = Math.round(opts.fade * 1000);
		if (opts.sleep)
			var sleep = Math.round(opts.sleep * 1000);
		if (opts.speed)
			var speed = opts.speed / 1000,
					fade_px = Math.round(fade_ms * speed);

		// set container css
		self.empty().css({
			overflow: 'hidden',
			padding: 0
		});
		if (! self.css('position').match(/absolute|relative|fixed/))
			self.css({ position: 'relative' });
		if (! self.width() || ! self.height())
			abort('container element does not have its own width and height');

		// random sorting
		if (opts.shuffle)
			plan.sort(function() {
				return Math.random() - 0.5;
			});

		// prepare each image
		for (var i = 0; i < plan.length; ++i) {

			var p = plan[i];
			if (! p.src)
				abort('missing src parameter in picture {0}.', i + 1);

			if (speed) { // speed/dir mode

				// check parameters and translate speed/dir mode into full mode (from/to/time)
				switch (p.dir) {
					case 'up':
						p.from = { xrel: .5, yrel: 0, zoom: 1 };
						p.to   = { xrel: .5, yrel: 1, zoom: 1 };
						var slide_px = p.height - self_height - 2 * fade_px;
						break;
					case 'down':
						p.from = { xrel: .5, yrel: 1, zoom: 1 };
						p.to   = { xrel: .5, yrel: 0, zoom: 1 };
						var slide_px = p.height - self_height - 2 * fade_px;
						break;
					case 'left':
						p.from = { xrel: 0, yrel: .5, zoom: 1 };
						p.to   = { xrel: 1, yrel: .5, zoom: 1 };
						var slide_px = p.width - self_width - 2 * fade_px;
						break;
					case 'right':
						p.from = { xrel: 1, yrel: .5, zoom: 1 };
						p.to   = { xrel: 0, yrel: .5, zoom: 1 };
						var slide_px = p.width - self_width - 2 * fade_px;
						break;
					default:
						abort('missing or malformed "dir" parameter in picture {0}.', i + 1);
				}
				if (slide_px <= 0)
					abort('picture number {0} is too short for the desired fade duration.', i + 1);
				p.time_ms = Math.round(slide_px / speed);

			} else if (! sleep) { // full mode

				// check and parse parameters
				if (! p.from || ! p.to || ! p.time)
					abort('missing either speed/sleep option, or from/to/time params in picture {0}.', i + 1);
				try {
					p.from = parse_position_param(p.from)
				} catch (e) {
					abort('malformed "from" parameter in picture {0}.', i + 1);
				}
				try {
					p.to = parse_position_param(p.to)
				} catch (e) {
					abort('malformed "to" parameter in picture {0}.', i + 1);
				}
				if (! p.time)
					abort('missing "time" parameter in picture {0}.', i + 1);
				p.time_ms = Math.round(p.time * 1000)
			}

			// precalculate left/top/width/height bounding values
			if (p.from)
				jQuery.each([ p.from, p.to ], function(i, from_to) {
					from_to.width  = Math.round(p.width  * from_to.zoom);
					from_to.height = Math.round(p.height * from_to.zoom);
					from_to.left   = Math.round((self_width  - from_to.width)  * from_to.xrel);
					from_to.top    = Math.round((self_height - from_to.height) * from_to.yrel);
				});

			// append the image (or anchor) element to the container
			var elm;
			if (p.href)
				elm = jQuery(format('<a href="{0}"><img src="{1}"/></a>', p.href, p.src));
			else
				elm = jQuery(format('<img src="{0}"/>', p.src));
			if (p.onclick)
				elm.click(p.onclick);
			elm.appendTo(self);
		}
		speed = undefined;  // speed mode has now been translated to full mode

		// find images to animate and set initial css attributes
		var imgs = self.find('img').css({
			position: 'absolute',
			visibility: 'hidden',
			top: 0,
			left: 0,
			border: 0
		});

		// show first image
		imgs.eq(0).css({ visibility: 'visible' });
		if (! sleep)
			imgs.eq(0).css(position_to_css(plan[0], 2));

		// create animation chain
		var countdown = opts.loop;
		function create_chain(i, chainf) {
			// building the chain backwards, or inside out

			if (i % 2 == 0) {
				if (sleep) {

					// still image sleep

					var i_sleep = i / 2,
							i_hide = (i_sleep - 1 + plan.length) % plan.length,
							img_sleep = imgs.eq(i_sleep),
							img_hide = imgs.eq(i_hide);

					var newf = function() {
						img_hide.css('visibility', 'hidden');
						setTimeout(chainf, sleep);
					};

				} else {

					// single image slide

					var i_slide = i / 2,
							i_hide = (i_slide - 1 + plan.length) % plan.length,
							img_slide = imgs.eq(i_slide),
							img_hide = imgs.eq(i_hide),
							time = plan[i_slide].time_ms,
							slide_anim = position_to_css(plan[i_slide], 3);

					var newf = function() {
						img_hide.css('visibility', 'hidden');
						img_slide.animate(slide_anim, time, 'linear', chainf);
					};

				}
			} else {
				if (sleep) {

					// still image cross-fade

					var i_from = Math.floor(i / 2),
							i_to = Math.ceil(i / 2) % plan.length,
							img_from = imgs.eq(i_from),
							img_to = imgs.eq(i_to),
							from_anim = {},
							to_init = { visibility: 'visible' },
							to_anim = {};

					if (i_to > i_from) {
						to_init.opacity = 0;
						to_anim.opacity = 1;
					} else {
						from_anim.opacity = 0;
					}

					var newf = function() {
						img_to.css(to_init);
						if (from_anim.opacity != undefined)
							img_from.animate(from_anim, fade_ms, 'linear', chainf);
						else
							img_to.animate(to_anim, fade_ms, 'linear', chainf);
					};

				} else {

					// cross-slide + cross-fade

					var i_from = Math.floor(i / 2),
							i_to = Math.ceil(i / 2) % plan.length,
							img_from = imgs.eq(i_from),
							img_to = imgs.eq(i_to),
							from_anim = position_to_css(plan[i_from], 4),
							to_init = position_to_css(plan[i_to], 1),
							to_anim = position_to_css(plan[i_to], 2);

					if (i_to > i_from) {
						to_init.opacity = 0;
						to_anim.opacity = 1;
					} else {
						from_anim.opacity = 0;
					}
					to_init.visibility = 'visible';

					var newf = function() {
						img_from.animate(from_anim, fade_ms, 'linear');
						img_to.css(to_init);
						img_to.animate(to_anim, fade_ms, 'linear', chainf);
					};

				}
			}

			// if the loop option was requested, push a countdown check
			if (opts.loop && i == plan.length * 2 - 2) {
				var newf_orig = newf;
				newf = function() {
					if (--countdown) newf_orig();
				}
			}

			if (i > 0)
				return create_chain(i - 1, newf);
			else
				return newf;
		}
		var animation = create_chain(plan.length * 2 - 1, function() { return animation(); });

		// start animation
		animation();

	});

	return self;
};

/*#################################### End of jquery.cross-slide.js ########################################*/
