var isel_level = 0; // level of selects to hide
var s_log_string = ''; // logging of user actions
var wait_timer=null;  // reference to wait logo timeout 
var bAllowOpen = true;	
var gsmoffset=0;
var bTimer;
var onloads = new Array();	
var imar = new Array();

var ua_ag = (navigator==null||navigator.userAgent==null)?'':navigator.userAgent.toLowerCase();
var ua_op = (ua_ag.indexOf('opera')!=-1);
var ua_ie = !ua_op&&(ua_ag.indexOf('msie')!=-1);
var ua_fx = (ua_ag.indexOf('firefox')!=-1);




function ipage() {	
window.onerror=cerror;
alert(onloads.length);
		for ( var i = 0 ; i < onloads.length; i++ ) onloads[i]();

		preload_images('tr/i-bottom.gif','tr/i-repeater.gif','tr/l.gif','tr/minus.gif','tr/page-file.png','tr/page-foldericon.png','tr/page-openfoldericon.png','tr/plus.gif','tr/t.gif', 'lft_tas.gif', 'lft_cal.gif', 'lft_con.gif', 'lft_hlp.gif', 'lft_not.gif', 'lft_set.gif', 'lft_snc.gif', 'loading.gif','vc/em.gif','vc/fax.gif','vc/mb.gif','vc/mr.gif','vc/or.gif','vc/pg.gif','vc/ph.gif','vc/vc.gif','vc/ww.gif','indi3.gif')
}	


function preload_images(){
		for (var x=0; x<preload_images.arguments.length; x++){
				imar[x] = new Image();
				imar[x].src = 'img/'+preload_images.arguments[x];
		}
}

function weho_error(msg)
{
	alertw(msg);	
	wait_hide(0);
	return true
}    

function cerror(msg, url, linen){
var sHtml=synci.cm_unspecified_error+'<br/><br/>';
sHtml += '<a href="javascript:err_dt.style.display=\'block\';void(0);" style="font-size:9px">'+synci.cm_more_details+'</a>';
sHtml += '<div style="display:none" id="err_dt" style="font-size:10px">';
sHtml += 'err:'+msg+'<br/>';
sHtml += 'ln:'+linen+'<br/>';		
sHtml += 'p:'+url+'<br/>';	
sHtml += 'u:'+unescape(readCookie('uid'))+'<br/>';				
sHtml += s_log_string;
sHtml += '</div>'

		var opt = {method:'get', parameters:'saction=logerror&uid='+readCookie('uid')+'&err='+escape(msg)+'&line='+escape(linen)+'&url='+escape(url)+'&log='+escape(s_log_string)};
alert(synci.ajax_url);
var aj = new Ajax.Request(synci.ajax_url,opt)		

alertw(sHtml);	
wait_hide(0);
return true
}

function fnn(a) {
if (fnn.caller!=null) {
	var s = fnn.caller.toString();
	var n = s.split ('(')[0];
		n=n.split (/[' '{1,}]/)[1]+'(';
	for (i=0; i<a.length; i++) {
		n+=typeof(a[i]) + ':' + a[i];
		n+= i<a.length-1 ? ',' : '';
	}
	s_log_string += n+')<br/>';
	return n+')';		
}
}

//wait logo funcs
function wait_show(){
if (wait_timer==null) {
	var d = document;
	var b = document.getElementsByTagName('body');	
	var im = cr('img')
	im.id = 'wait_logo';
	im.className = 'wait_logo';
	im.src='img/loading.gif';
	im.style.visibility='hidden';
	ap(b[0],im);

	var IpopTop = (document.body.clientHeight - im.offsetHeight) / 2;
	var IpopLeft = (document.body.clientWidth - im.offsetWidth-220) / 2;

	im.style.width=220;
	im.style.height=19;

	im.style.left=IpopLeft + document.body.scrollLeft;
	im.style.top=IpopTop + document.body.scrollTop;


	//im.style.top = (d.documentElement.scrollHeight - im.offsetHeight-200)/2 + "px";
	//im.style.left = (d.documentElement.scrollWidth - im.offsetWidth)/2 + "px";	
	im.style.visibility='visible';	
} else {
	clearTimeout(wait_timer);
	wait_timer = null;
}
}


function wait_hide(i_timer){
wait_timer = setTimeout(wait_hide_now,i_timer);
}

function wait_hide_now()
{
if ($('wait_logo')!=null)
	document.getElementsByTagName('body')[0].removeChild($('wait_logo'));
wait_timer = null;
}

function bo(){ // block opening on clicks 
bAllowOpen = false;
		setTimeout(function(){bAllowOpen = true;},100);	
}

function confirmw(txt, fOk, fCancel) {
		alertw(txt, function(){alertClose();fOk();}, null, 'alert_confirm.asp', function(){alertClose();fCancel();});
}




function url_ch(sname,svalue){
	var surl = window.location.href;
	var sres = '';
	var a = surl.split('#');
	if (a.length==1)
			sres = surl + '#' + sname + '=' + svalue;
	else {
			if (a[1]!=''){
					sres = a[0] + '#';
					var b = a[1].split('&');
					var present = false;
					for (i=0;i<b.length;i++) {
							var c = b[i].split('=');
							if (c[0]==sname){
									if (svalue!='') sres += c[0] + '=' + svalue + (i<b.length-1?'&':'');
									present = true;
							} else
									sres += c[0] + '=' + c[1] + (i<b.length-1?'&':'');
					}
					if (!present && svalue!='')
							sres+= '&' + sname + '=' + svalue;
			} else if (svalue!='')
					sres+= a[0] + '#' + sname + '=' + svalue;
	}
	while (sres.substr(sres.length-1,1)=='&')
			sres = sres.substr(0,sres.length-1);
	if (sres!='') window.location.href=sres;
}

function show_page_by_url(){
		var surl = window.location.href;
		var a = surl.split('#');
		if (a.length>1)
			if (a[1]!=''){
				var b = a[1].split('&');
				for (i=0;i<b.length;i++) {
					 var c = b[i].split('=');
					 if (c[0]=='screen') {
								switch (c[1]) {
										case 'contacts' : showContentForm('p_con',0); break;
										case 'tasks' : showContentForm('p_tas',0); break;
										case 'calendar' : showContentForm('p_cal',0); break;
										case 'notes' : showContentForm('p_not',0); break;
										case 'backups' : showContentForm('p_snc',0); break;
										case 'settings' : showContentForm('p_set',0); break;
										case 'last_sync' : showContentForm('last_sync',0); break;
										case 'shared_contacts' : showContentForm('shared_contacts',0); break;
										case 'common_calendar' : showContentForm('common_calendar',0); break;
								}
					 }
					 if (c[0]=='help') getHelp(c[1]);

				}
			}
}

// alert and modal functions    	
function alertw(txt, fInsteadClose, no_rep_cookie_name, sTemplatePage, fCancel, fOnLoad)
{
		var opt = {
				method: 'get', 
				onComplete : function alertShow(or){
												var d = document; var b = document.getElementsByTagName('body');	
												alert_div = $('alert_div');
													if ($('alert_div')==null) {
											alert_div = cr('div');
											alert_div.id = 'alert_div';
											alert_div.name = 'alert_div_4dg';
											ap(b[0],alert_div);	
											modalShow('alert_div');
												}
								alert_div.onmousedown = function(){try {dragStart(event, this.id);} catch (e) {false;}};
								alert_div.innerHTML = or.responseText;
								$('alert_message').innerHTML = txt;
								// disable title selection
								if ($('alert_title')!=null) $('alert_title').onselectstart=function (){return false;};


								if (fInsteadClose==null)
									$('alert_ok').onclick = $('alert_close').onclick = alertClose;
								else
									$('alert_ok').onclick = $('alert_close').onclick = fInsteadClose;

								if (fCancel!=null)
										$('alert_cancel').onclick = $('alert_close').onclick = fCancel;

								if (no_rep_cookie_name!=null) {
									$('alert_no_repeat').style.display='block';
									$('norep_chk').value=no_rep_cookie_name;
								}

								//alert_div.style.top = (d.documentElement.scrollHeight - alert_div.offsetHeight)/2 + "px";
								//alert_div.style.left = (d.documentElement.scrollWidth - $('alert_message').offsetWidth)/2 + "px";
								//if (d.documentElement.scrollHeight - alert_div.offsetHeight < 5) alert_div.style.top = '5px';
								
								var IpopTop = (document.body.clientHeight - alert_div.offsetHeight) / 2;
								var IpopLeft = (document.body.clientWidth - alert_div.offsetWidth) / 2;

								alert_div.style.left=IpopLeft + document.body.scrollLeft;
								alert_div.style.top=IpopTop + document.body.scrollTop;	

								alert_div.style.display='block';
								if (fOnLoad!=null) fOnLoad();
							}						
				}
			if (sTemplatePage==null) sTemplatePage = 'alert.php';
			sTemplatePage = sTemplatePage;
			var aj = new Ajax.Request(sTemplatePage,opt);
}						

function alertClose(){
if ($('alert_div')!=null) 
{
	modalHide('alert_div');
	document.getElementsByTagName('body')[0].removeChild($('alert_div'));
}

}

function modalShow(obj_id){
	var d = document; var b = document.getElementsByTagName('body');
		if (!document.getElementById('dmodal'+obj_id)) {
		//alert("in" + document.body.scrollHeight);
			var mObj = b[0].appendChild(d.createElement('div'));
			mObj.style.zIndex = parseInt(getStyle($(obj_id),'z-index')) -1;
			//mObj.style.height = "3120px";
			mObj.style.height = document.body.scrollHeight+"px";
			mObj.id = 'dmodal'+obj_id;
			mObj.className = 'dmodal';					
		}
		hideSelects(isel_level++);

}
function modalHide(obj_id){
if ($('dmodal'+obj_id)!=null) {
	document.getElementsByTagName("body")[0].removeChild($('dmodal'+obj_id));
	hideSelects(--isel_level,true); 		
}
}

//help page functions
function lhlp(n_help_id){
if (n_help_id!=null) {
	var o = $('hl'+n_help_id);	
	if (o.getAttribute('has_text')=='0') return true;
	$('hlp_content').setAttribute('help_id',n_help_id);}
else {
	n_help_id = $('hlp_content').getAttribute('help_id');
	var o = $('hl'+n_help_id);				
}
if (o!=null) o.style.color='green';
var c_parent = o.parentNode;
while (c_parent.id!='help_nav_tree') {
		removeClass(c_parent,'spanClosed');
		removeClass(c_parent,'closed');				
		c_parent = c_parent.parentNode;
	}

var old_help_id = $('hlp_content').getAttribute('old_help_id');
if ((old_help_id!='') && (old_help_id!=null)) $('hl'+old_help_id).style.color='';
$('hlp_content').setAttribute('old_help_id',n_help_id);

url_ch('help',n_help_id);
var aj = new Ajax.Request(synci.ajax_url,{method: 'get', parameters: 'saction=gethelp&help_id='+n_help_id, onComplete: shlp})
}
function shlp(or){
$('hlp_content').innerHTML=or.responseText;
$('edit_block').value = or.responseText;
}	
function save_help(){
var sxml = '<root>' + xCD($('edit_block').value) + '</root>';
var opt = {method:'post', onComplete:save_help_ok, postBody:sxml};
var aj = new Ajax.Request(synci.ajax_url+'?saction=save_help&help_id='+$('hlp_content').getAttribute('help_id'),opt)
}
function save_help_ok(or){
hd_block('hlp_content',false);
hd_block('edit_block',true);
lhlp();
}

function edit_help(){
if ($('edit_block').style.display=='block')
	save_help()
else {
	hd_block('hlp_content',true);
	hd_block('edit_block',false);
}
}


function getHelp(help_id) {
wait_show();
url_ch('screen','');
url_ch('help',help_id);
	var aj = new Ajax.Request(synci.ajax_url,{method: 'get', parameters: 'saction=gethelp&help_id='+help_id, onComplete: getHelp_ok})    
}

function getHelp_ok(or){
wait_hide(0);    
		var s = or.responseText; 
		var re = /lhlp\(/g; reImg = /<img src/g;
				s = s.replace(re,'getHelp(');
				s = s.replace(reImg,'<img style=\'display:none\' src');

		alertw(s,null,null,'alert_help.asp',null,function (){if (ua_fx) $('alert_message').style.width='93%';});
}

//end help functions


//effects 
function trs(obj){
	for (i=0;i<obj.childNodes.length;i++)	
			obj.childNodes[i].style.backgroundColor = '#F5F5F5'
}
function trc(obj){
	for (i=0;i<obj.childNodes.length;i++)	
			obj.childNodes[i].style.backgroundColor = '';
}	

	function sel_chk(obj_id){
		this.cc_selected = (this.cc_selected ? false : true);
		var objs = document.getElementsByTagName('input');
		for (i=0;i<objs.length;i++) {
			if (objs[i].type=='checkbox' && objs[i].id==obj_id) objs[i].checked=this.cc_selected;
			}
	}	

		function change_chk(obj_name){
				var obj = $(obj_name);
				if (obj!=null) obj.checked=!obj.checked
		}


// login and settings
function popBrands(brand_id,phone_id,clearBefore){
populateSelect('phone_brand_id',arrBrands,clearBefore,brand_id);
$('phone_brand_id').onchange=popModels;
$('phone_id').onchange=preparePhoneInfo;
popModels(phone_id, brand_id);
}
function popModels(phone_id, brand_id){
var ibrand_id = (brand_id==null) ? parseInt($('phone_brand_id').options[$('phone_brand_id').selectedIndex].value) : brand_id;
if (ibrand_id==-1) {
	populateSelect('phone_id',Array(),true);
	$('phone_id').disabled=true;
} else {
	populateSelect('phone_id',arrPhones[ibrand_id],true,phone_id);
	$('phone_id').disabled=false;
}
preparePhoneInfo();
}
function preparePhoneInfo(){
var ph_id = $('phone_id').value;
if (arrPhoneNotes[ph_id]!=null) {
	$('phone_info').onclick=function (){alertw(arrPhoneNotes[ph_id]);};
	$('phone_info').style.display='inline';
} else {
	$('phone_info').style.display='none';
}
}	


// common logic functions 
function isloged(){
//if (readCookie('uid')=='' || readCookie('uid')==null) {
//	alertw(synci.cm_session_expired,function(){alertClose();logoff();});
//	return false;
//}
//else
	return true;
} 	
function logoff(){
window.location.href='default.asp?saction=logoff'
}


function check_ta_len(o,ml){
		if (o.value.length >= ml)
				o.value = o.value.substring(0,ml);
}


function cr(tag){return document.createElement(tag);}
function ap(par,el){return par.appendChild(el);}	

function populateSelect(obj_id, arr, clearBefore, selValue) {
var osel = $(obj_id);
var start_poz=0;
if (osel!=null) {
	if (clearBefore) 
		osel.length=0;
	else
		start_poz = osel.length;
	for (i=0; i<arr.length; i+=2) {
			osel.options[start_poz + i/2] = new Option(arr[i+1],arr[i]);
			if ((selValue!=null) && (arr[i].toString()==selValue.toString())) 
				{ osel.selectedIndex = start_poz + i/2;}
		}
}
}

function changeSelect(obj, sval) {
	for (var i=0;i<obj.options.length;i++)
			if (obj.options[i].value==sval) obj.selectedIndex = i;
}

function hideSelects(ilevel,isshow){
var sels=document.getElementsByTagName("select");
for(i=0; i<sels.length; i++){ 
	clev = sels[i].getAttribute('level')
	if (clev==null) {sels[i].setAttribute('level',0);clev=0}
	if (parseInt(clev)==ilevel) 
		sels[i].style.visibility = isshow ? 'visible' : 'hidden'
}
}

// hides and unhindes item
function hd_block(obj_id, is_hide){
var obj = $(obj_id);
if (obj!=null) 
	if (is_hide)
		{obj.style.display='';obj.style.display='none';}
	else						 
		{obj.style.display='block';}
}			   					   

//cookies utils
function createCookie(name,value,days)
{
if (days)
{
	var date = new Date();
	date.setTime(date.getTime()+(days*24*60*60*1000));
	var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = escape(name)+"="+value+expires+"; path="+synci.cookies_path;

}

function readCookie(name)
{
var nameEQ = escape(name) + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++)
{
	var c = ca[i];
	while (c.charAt(0)==' ') c = c.substring(1,c.length);
	if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}

function eraseCookie(name)	{createCookie(name,"",-1);}

function loadHome(){}
function loadDesk(){}	


function ApplyEvents(arrRules){			   
for (selector in arrRules){
		var stype = selector.split(':')[0];
		var svalue = selector.split(':')[1];
		var spArr = svalue.split(',');					  
		var oc = new Array();					  

		if (stype=='id') 
			for (j=0;j < spArr.length; j++)	
				if (document.getElementById(spArr[j])!=null) arrRules[selector](document.getElementById(spArr[j]));

		if (stype=='class')
			for (j=0;j < spArr.length; j++){
				oc = document.getElementsByClassName(spArr[j]);
				for (i=0; i < oc.length; i++)	arrRules[selector](oc[i]);					  
		}
		if (stype=='tag')
			for (j=0;j < spArr.length; j++){
				oc = document.getElementsByTagName(spArr[j]);
				for (i=0; i < oc.length; i++)	arrRules[selector](oc[i]);					  
		}
}

}			

/* forms logic */

function checkEmail(sValue) {
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(sValue))
	return (true);
else
	return (false);
}


/* date functions */

function show_current_time(){
	if (arguments.length!=0) gsmoffset = arguments[0]
	var obj = $('time_info');
	var dt = new Date();
		dt.setHours(dt.getHours()+gsmoffset);
	var sdt = dt.getUTCDate()+'.'+(dt.getUTCMonth()+1)+'.'+dt.getUTCFullYear()+' '+dt.getUTCHours()+':'+add0(dt.getUTCMinutes())+' (GMT+'+gsmoffset+')';
	if (obj.innerText!=sdt) obj.innerText=sdt;
		setTimeout(show_current_time,1000);
}

function add0(s){
	if (String(s).length==0)
			return '00'
	else if (String(s).length==1)
			return '0'+s
	else
				return s+''	    
}

function gmt_offset(){
	 var d = new Date();
	 return( -1 * d.getTimezoneOffset() / 60);
}	

function validateDate( strValue, retDate) {
strValue = strValue.trim();
var re = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}(\s\d{1,2}\:\d{1,2})?$/
if(!re.test(strValue))
return false; 
else {
var isOkDate = false;
if (strValue.split(' ').length==2){
	var strDate = strValue.split(' ')[0];
	var strTime = strValue.split(' ')[1];
}
else {
	var strDate = strValue;
	var strTime = '';
}

var strSeparator = '.'; //strDate.substring(2,3) 	
var arrayDate = strDate.split(strSeparator); //split date into month, day, year

var arrayLookup = { '01' : 31,'03' : 31, '04' : 30,'05' : 31,'06' : 30,'07' : 31, '08' : 31,'09' : 30,'10' : 31,'11' : 30,'12' : 31}
var intDay = arrayDate[0];

if(arrayLookup[arrayDate[1]] != null) {
if(intDay <= arrayLookup[arrayDate[1]] && intDay != 0)
	isOkDate = true; 
}

var intMonth = parseFloat(arrayDate[1]);
var intYear = parseFloat(arrayDate[2]);		
if (intMonth == 2) { 
if( ((intYear % 4 == 0 && intDay <= 29) || (intYear % 4 != 0 && intDay <=28)) && intDay !=0)
	isOkDate = true; 
}
if (isOkDate) {
	if (strTime=='' || ((parseInt(strTime.split(':')[0])<24) && (parseInt(strTime.split(':')[1])<60)))
		isOkDate = true; 
	else
		isOkDate = false; 
}
if (retDate==null)
		return isOkDate;
else {
		var dtRet;
		dtRet = new Date(intYear, intMonth-1, intDay,strTime.split(':')[0],strTime.split(':')[1]);
		return dtRet;
}
}

}

function getWeek(dt){
		var year = dt.getFullYear();
		var month = dt.getMonth()+1;
		var day = dt.getDate();
		var a = Math.floor((14-(month))/12);
		var y = year+4800-a;
		var m = (month)+(12*a)-3;
		var jd = day + Math.floor(((153*m)+2)/5) + 
								 (365*y) + Math.floor(y/4) - Math.floor(y/100) + 
								 Math.floor(y/400) - 32045;
		var d4 = (jd+31741-(jd%7))%146097%36524%1461;
		var L = Math.floor(d4/1460);
		var d1 = ((d4-L)%365)+L;
		NumberOfWeek = Math.floor(d1/7) + 1;
		return NumberOfWeek;        
}

function frDate(dt){
return dt.getDate() +'.'+fr02(dt.getMonth()+1)+'.'+dt.getFullYear()+' ' + fr02(dt.getHours()) + ':' + fr02(dt.getMinutes());
}


function fr02(sval){;return (String(sval).length == 1) ? '0' + sval : sval;}	


String.prototype.trim = function() {return this.replace(/^\s+|\s+$/, '');}

/* visual effects */ 


	function FadeTextIn(obj_id){
			$(obj_id).style.color='';
	}
	function FadeTextOut(obj_id){					 
			$(obj_id).style.color='#6152FA';
	}


function getStyle(element, style) {
var value = element.style[style.camelize()];
if (!value) {
	if (document.defaultView && document.defaultView.getComputedStyle) {
		var css = document.defaultView.getComputedStyle(element, null);
		value = css ? css.getPropertyValue(style) : null;
	} else if (element.currentStyle) {
		value = element.currentStyle[style.camelize()];
	}
}

if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
	if (Element.getStyle(element, 'position') == 'static') value = 'auto';

return value == 'auto' ? null : value;
}


function loadjs(lName) {
		var html_doc = document.getElementsByTagName('head').item(0);
		var js = document.createElement('script');
		js.setAttribute('language', 'javascript');
		js.setAttribute('type', 'text/javascript');
		js.setAttribute('src', lName);
		html_doc.appendChild(js);
		return false;
}
/*************************************************************/
var bLoadingForm = false;
var timerId = "";
function showForm(form_name, item_id,mode,id){
		if (!bLoadingForm) {
				bLoadingForm = true;
			alertClose();	        
			fnn(arguments);		    
			//wait_show();
			if (!isloged())	return false;
			var s_form_div_id = (arguments.length==3) ? arguments[2] : 'form_div';		
			var opt = {
					method: 'get', 
					onComplete : function showIt(or){
									fnn(arguments);
									var d = document; var b = document.getElementsByTagName('body');	
									form_div = cr('div');
									form_div.id = s_form_div_id;
									ap(b[0],form_div);	
									modalShow(s_form_div_id);
									form_div.innerHTML = or.responseText;
																	form_div.onmousedown = function(){try {dragStart(event, this.id)} catch (e) {}};

									var sels = form_div.getElementsByTagName('select');
									for (i=0; i<sels.length; i++)
										sels[i].setAttribute('level',isel_level);

									if ($('form_title')!=null) $('form_title').onselectstart=function (){return false;};
									if ($('form_title_table')!=null) $('form_title_table').onselectstart=function (){return false;};

									if ($('form_ok')!=null)
										if ($('form_ok').onclick==null) $('form_ok').onclick = function () {eval('save_'+form_name+'('+item_id+')');};
									if ($('form_cancel')!=null)
										if ($('form_cancel').onclick==null) $('form_cancel').onclick = function formClose(){b[0].removeChild($(s_form_div_id));modalHide(s_form_div_id);}
									if ($('form_close')!=null)
										if ($('form_close').onclick==null) $('form_close').onclick = function formClose(){b[0].removeChild($(s_form_div_id));modalHide(s_form_div_id);url_ch('screen','');url_ch('help','');clearInterval(timerId);}
									if ($('form_close_bottom')!=null)
										if ($('form_close_bottom').onclick==null) $('form_close_bottom').onclick = function formClose(){b[0].removeChild($(s_form_div_id));modalHide(s_form_div_id);url_ch('screen','');url_ch('help','');clearInterval(timerId);}

									if ($('form_close_top')!=null)
																			$('form_close_top').onclick = function formClose(){b[0].removeChild($(s_form_div_id));modalHide(s_form_div_id);clearInterval(timerId);}

									form_div.style.left = (d.documentElement.scrollWidth - form_div.offsetWidth)/2 + "px";
									form_div.style.top = (d.documentElement.scrollHeight - form_div.offsetHeight)/2 + "px";
										if (d.documentElement.scrollWidth - form_div.offsetWidth < 5) form_div.style.top = '5px';
									setTimeout(function(){form_div.style.display='block';bLoadingForm = false;},100);
									eval('init_'+form_name+'('+item_id+')');
									//wait_hide(50);									
								}						
					}
					//alert(form_name+'.php?pmode='+mode+'&id='+escape(id));
			var aj = new Ajax.Request(form_name+'.php?pmode='+mode+'&id='+escape(id),opt)	
	 }
}

function showContentForm(form_name, item_id,mode,id){
	fnn(arguments);
	showForm(form_name, item_id,mode,id,'content_form_div');
}		


///////////////////////////

var fst_step_number=1;

function init_actions(item_id)
{
		show_step(1);	  
}



function close_p_stp()
{
	$('form_close').onclick();
}	

function show_step(new_n) {
		if (new_n!=null) fst_step_number = new_n;

		$('step'+fst_step_number).style.display='block';

		var form_div = $('content_form_div');
		
		//form_div.style.left = (document.documentElement.scrollWidth - form_div.offsetWidth)/2 + "px";
		//form_div.style.top = (document.documentElement.scrollHeight - form_div.offsetHeight)/2 + "px";
		//if (document.documentElement.scrollHeight - form_div.offsetHeight < 5) form_div.style.top = '15px';	        
		//form_sub_div.style.height=form_div.offsetHeight+'px';
		
			var IpopTop = (document.body.clientHeight - form_div.offsetHeight) / 2;
			var IpopLeft = (document.body.clientWidth - form_div.offsetWidth) / 2;
		
			form_div.style.left=IpopLeft + document.body.scrollLeft;
			form_div.style.top=IpopTop + document.body.scrollTop;
			
			
			//form_div.style.left=IpopLeft + document.body.scrollLeft;
			//form_div.style.top=0;

			//newcontent();
			
			//docjslib_doThisCommandEveryIntervalMS("newcontent()", 10000);
			
			ContentSlider("slider1",3000) //or ContentSlider("slider1", 1000) to auto rotate every 3 seconds
			
}

function docjslib_doThisCommandEveryIntervalMS(command, interval)
{
	timerId = setInterval(eval('"' + command + '"'), interval);
}

/*****************************************************/

// Determine browser and version.
function Browser() {
	var ua, s, i;
	this.isIE    = false;
	this.version = null;
	ua = navigator.userAgent;

	s = "MSIE";
	if ((i = ua.indexOf(s)) >= 0) {
		this.isIE = true;
		this.version = parseFloat(ua.substr(i + s.length));
		return;
	}
}
var browser = new Browser();

var dragObj = new Object();

function dragStart(event, id) {
    if (!browser.isIE) return false;
	var el, bDrag = false;
	var x, y;
	var oSrc = event.srcElement;
	while (oSrc!=null && !bDrag) {
	    if (oSrc.id=='form_title_table' || oSrc.id=='form_title' || oSrc.id=='alert_title') bDrag = true;
	    oSrc = oSrc.parentElement;
	}
	if (!bDrag) return false;
	if (id)
		dragObj.elNode = document.getElementById(id)
	else {
		dragObj.elNode = window.event.srcElement;
		if (dragObj.elNode.nodeType == 3)
			dragObj.elNode = dragObj.elNode.parentNode;
	}

		x = window.event.clientX + document.documentElement.scrollLeft
			+ document.body.scrollLeft;
		y = window.event.clientY + document.documentElement.scrollTop
			+ document.body.scrollTop;

	dragObj.cursorStartX = x;
	dragObj.cursorStartY = y;
	dragObj.elStartLeft  = parseInt(dragObj.elNode.style.left, 10);
	dragObj.elStartTop   = parseInt(dragObj.elNode.style.top,  10);

	if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
	if (isNaN(dragObj.elStartTop))  dragObj.elStartTop  = 0;

	document.attachEvent("onmousemove", dragGo);
	document.attachEvent("onmouseup",   dragStop);
	window.event.cancelBubble = true;
	window.event.returnValue = false;
}

function dragGo(event) {
	var x, y;

	x = window.event.clientX + document.documentElement.scrollLeft
		+ document.body.scrollLeft;
	y = window.event.clientY + document.documentElement.scrollTop
		+ document.body.scrollTop;


	dragObj.elNode.style.left = (dragObj.elStartLeft + x - dragObj.cursorStartX) + "px";
	dragObj.elNode.style.top  = (dragObj.elStartTop  + y - dragObj.cursorStartY) + "px";

	window.event.cancelBubble = true;
	window.event.returnValue = false;
}

function dragStop(event) {
	document.detachEvent("onmousemove", dragGo);
	document.detachEvent("onmouseup",   dragStop);
}


/****************************/

/**************************************************************************************************************/
// Create xmlhttp object based on browsertype
function getHTTPObject() {
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
	  xmlhttp.overrideMimeType("text/xml"); 
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}
/**************************************************************************************************************/
// Define global variables to be used throughout
var tableBusy = false;
var tableHttp = getHTTPObject();

var step1Over = false;
var row = "";
/**************************************************************************************************************/
function getSortedNomination(perpage,orderby,insert_dir,id)
{
	if (!tableBusy)
	{
		var oid,sid;
		document.getElementById("loadingmsg").style.display="";
		var url = "actions.php";		
		var params = "pmode=nominate_sorting&id=" + id + "&perpage="+perpage+"&orderby="+orderby+insert_dir;
		tableHttp.open("POST", url, true);
		
		document.getElementById("loadingmsg").style.display="";	
		
		//Send the proper header infomation along with the request
		tableHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		tableHttp.setRequestHeader("Content-length", params.length);
		tableHttp.setRequestHeader("Connection", "close");
		
		tableHttp.onreadystatechange = getSortedNominationResponse;
	
		tableBusy = true;
		tableHttp.send(params);
	}
}

function getSortedNominationResponse()
{
	if (tableHttp.readyState == 4)
	{
		if (tableHttp.responseText.indexOf('invalid') == -1)
		{
			try
			{
				var output = tableHttp.responseText;
	
				// Draw Record status and nav buttons					
				tableBusy = false;
				
				document.getElementById("loadingmsg").style.display="none";
				document.getElementById("step1").innerHTML=output;
				
				//alert("output " + output );
				
				

			} // end try 
			catch(e)
			{
				alert("Error: " + e) ;
			} // end try catch
		} // end if response index -1
	} // end if readystate 4
} // end tableresponse function


function getPagingNominationStanding(perpage,orderby,insert_dir,id,startat,page_num,perpage,dir)
{
	if (!tableBusy)
	{
		var oid,sid;
		document.getElementById("loadingmsg").style.display="";
		var url = "actions.php";		
		var params = "pmode=nominate_standing_paging&id=" + id + "&perpage="+perpage+"&orderby="+orderby+"&dir="+dir+"&startat="+startat+"&perpage="+perpage+"&page_num="+page_num;
		tableHttp.open("POST", url, true);
		
		document.getElementById("loadingmsg").style.display="";	
		
		//Send the proper header infomation along with the request
		tableHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		tableHttp.setRequestHeader("Content-length", params.length);
		tableHttp.setRequestHeader("Connection", "close");
		
		tableHttp.onreadystatechange = getPagingNominationStandingResponse;
	
		tableBusy = true;
		tableHttp.send(params);
	}
}

function getPagingNominationStandingResponse()
{
	if (tableHttp.readyState == 4)
	{
		if (tableHttp.responseText.indexOf('invalid') == -1)
		{
			try
			{
				var output = tableHttp.responseText;
	
				// Draw Record status and nav buttons					
				tableBusy = false;
				
				document.getElementById("loadingmsg").style.display="none";
				document.getElementById("step1").innerHTML=output;
				
				//alert("output " + output );
				
				

			} // end try 
			catch(e)
			{
				alert("Error: " + e) ;
			} // end try catch
		} // end if response index -1
	} // end if readystate 4
} // end tableresponse function



function getPagingNomination(perpage,orderby,insert_dir,id,startat,page_num,perpage,dir)
{
	if (!tableBusy)
	{
		var oid,sid;
		document.getElementById("loadingmsg").style.display="";
		var url = "actions.php";		
		var params = "pmode=nominate_sorting&id=" + id + "&perpage="+perpage+"&orderby="+orderby+"&dir="+dir+"&startat="+startat+"&perpage="+perpage+"&page_num="+page_num;
		//alert(params);
		tableHttp.open("POST", url, true);
		
		document.getElementById("loadingmsg").style.display="";	
		
		//Send the proper header infomation along with the request
		tableHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		tableHttp.setRequestHeader("Content-length", params.length);
		tableHttp.setRequestHeader("Connection", "close");
		
		tableHttp.onreadystatechange = getPagingNominationResponse;
	
		tableBusy = true;
		tableHttp.send(params);
	}
}

function getPagingNominationResponse()
{
	if (tableHttp.readyState == 4)
	{
		if (tableHttp.responseText.indexOf('invalid') == -1)
		{
			try
			{
				var output = tableHttp.responseText;
	
				// Draw Record status and nav buttons					
				tableBusy = false;
				
				document.getElementById("loadingmsg").style.display="none";
				document.getElementById("step1").innerHTML=output;
				
				//alert("output " + output );
				
				

			} // end try 
			catch(e)
			{
				alert("Error: " + e) ;
			} // end try catch
		} // end if response index -1
	} // end if readystate 4
} // end tableresponse function



function getPagingNominationByUser(perpage,orderby,insert_dir,id,startat,page_num,perpage,dir)
{
	if (!tableBusy)
	{
		var oid,sid;
		document.getElementById("loadingmsg").style.display="";
		var url = "actions.php";		
		var params = "pmode=nominate_sorting&id=" + id + "&perpage="+perpage+"&orderby="+orderby+"&dir="+dir+"&startat="+startat+"&perpage="+perpage+"&page_num="+page_num;
		//alert(params);
		tableHttp.open("POST", url, true);
		
		document.getElementById("loadingmsg").style.display="";	
		
		//Send the proper header infomation along with the request
		tableHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		tableHttp.setRequestHeader("Content-length", params.length);
		tableHttp.setRequestHeader("Connection", "close");
		
		tableHttp.onreadystatechange = getPagingNominationByUserResponse;
	
		tableBusy = true;
		tableHttp.send(params);
	}
}

function getPagingNominationByUserResponse()
{
	if (tableHttp.readyState == 4)
	{
		if (tableHttp.responseText.indexOf('invalid') == -1)
		{
			try
			{
				var output = tableHttp.responseText;
	
				// Draw Record status and nav buttons					
				tableBusy = false;
				
				document.getElementById("loadingmsg").style.display="none";
				document.getElementById("step1").innerHTML=output;
				
				//alert("output " + output );
				
				

			} // end try 
			catch(e)
			{
				alert("Error: " + e) ;
			} // end try catch
		} // end if response index -1
	} // end if readystate 4
} // end tableresponse function



function nominateWebsite(listing_id)
{
	if (!tableBusy)
	{
		var oid,sid;
		document.getElementById("loadingmsg").style.display="";
		var url = "actions.php";		
		var params = "pmode=nominateWebsite&listing_id="+listing_id;
		tableHttp.open("POST", url, true);
		
		document.getElementById("loadingmsg").style.display="";	
		
		//Send the proper header infomation along with the request
		tableHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		tableHttp.setRequestHeader("Content-length", params.length);
		tableHttp.setRequestHeader("Connection", "close");
		
		tableHttp.onreadystatechange = nominateWebsiteResponse;
	
		tableBusy = true;
		tableHttp.send(params);
	}
}

function nominateWebsiteResponse()
{
	if (tableHttp.readyState == 4)
	{
		if (tableHttp.responseText.indexOf('invalid') == -1)
		{
			try
			{
				var output = tableHttp.responseText;
	
				// Draw Record status and nav buttons					
				tableBusy = false;
				
				document.getElementById("loadingmsg").style.display="none";
		
				// split the output
				var outputString = output;
				var outputArr = new Array();
				outputArr = outputString.split("_");
		
				if (outputArr[0] == "1")
				{
				  weho_error("You can only nominate 3 blogs per category.");
				}
				else if (outputArr[0] == "2")
				{
				  weho_error("Your nomination has been recorded.");
				  updateNominationCategory(outputArr[1]);
				}
				else if (outputArr[0] == "3")
				{
					weho_error("Your have already nominated this blog.");
				}

				

			} // end try 
			catch(e)
			{
				alert("Error: " + e) ;
			} // end try catch
		} // end if response index -1
	} // end if readystate 4
} // end tableresponse function


function updateNominationCategory(id)
{
	if (!tableBusy)
	{
		var oid,sid;
		document.getElementById("loadingmsg").style.display="";
		var url = "actions.php";		
		var params = "pmode=updateNominationBlogCount&id=" + id;
		//alert(params);
		tableHttp.open("POST", url, true);
		
		document.getElementById("loadingmsg").style.display="";	
		
		//Send the proper header infomation along with the request
		tableHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		tableHttp.setRequestHeader("Content-length", params.length);
		tableHttp.setRequestHeader("Connection", "close");
		
		tableHttp.onreadystatechange = updateNominationCategoryResponse;
	
		tableBusy = true;
		tableHttp.send(params);
	}
}

function updateNominationCategoryResponse()
{
	if (tableHttp.readyState == 4)
	{
		if (tableHttp.responseText.indexOf('invalid') == -1)
		{
			try
			{
				var output = tableHttp.responseText;
	
				// Draw Record status and nav buttons					
				tableBusy = false;
				
				document.getElementById("loadingmsg").style.display="none";
		
				// split the output
				var outputString = output;
				var outputArr = new Array();
				outputArr = outputString.split("<<:|>>");
				document.getElementById("nominatedblog_"+outputArr[1]).innerHTML="Total Nominations: "+outputArr[0];

			} // end try 
			catch(e)
			{
				alert("Error: " + e) ;
			} // end try catch
		} // end if response index -1
	} // end if readystate 4
} // end tableresponse function