var mainpage_sender=null;
var selectWindow=null;
var cc=null;
var prov=null;

/* MACROMEDIA IMAGE PRELOADING FUNCTIONS */

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr;
  for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; 
	if(d.images){ 
		if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; 
		for(i=0; i<a.length; i++)
			if (a[i].indexOf("#")!=0) { 
				d.MM_p[j]=new Image;
				d.MM_p[j++].src=a[i];
			}
	}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  
	if(!d) d=document; 
	if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; 
		n=n.substring(0,p);
	}
  if(!(x=d[n])&&d.all) x=d.all[n]; 
	for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) 
		x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
	var i,j=0,x,a=MM_swapImage.arguments; 
	document.MM_sr=new Array; 
	for(i=0;i<(a.length-2);i+=3)
		if ((x=MM_findObj(a[i]))!=null){
			document.MM_sr[j++]=x; 
			if(!x.oSrc) x.oSrc=x.src; 
			x.src=a[i+2];
		}
}

/* UNIQUE FUNCTIONS */

function grab_user_data(x){
	x.user_width.value = screen.width ? screen.width : 0;
	x.user_height.value = screen.height ? screen.height : 0;
	x.user_bpp.value = screen.pixelDepth ? screen.pixelDepth : screen.colorDepth;
	return true;
}

function yesclock(tz) {
	if (document.images) {
		setTimeout("renewClock("+tz+")",60000);
	}
}

function renewClock(tz) {
	var x=document.images["clock"];
	/* alert("Clock reloading!"); */
	x.src="/mkclock.php?tz="+tz+"&dummy="+((Math.random()).toString()).replace(".","");
}

function popup_image(img_id,section) {
	window.open("/misc/show_image.php?id="+img_id+"&section="+section,"",
							"width=640,height=480,toolbar=no,scrollbars=no");
}

/* used from show_image.php */
function zoomImage(url,width,height){
	var myRnd="pw"+((Math.random()).toString()).replace(".","");
	
	var pw=window.open("",myRnd,"toolbar=no,scrollbars=no,width="+(width+20)+",height="+(height+20));

	pw.document.write("<html><head><title>Image "+url+"</title></head><body>");
	pw.document.write("<img src='"+url+"'></body></html>");
	return false;
}

/* sas == "set and submit". Arguments are:

   y: calling element (which is inside a form!)
   args: a list of value pairs (element name: string, element value: mixed)

	  The argument may also be "action" or "method", which then redirects the 
		 form to another page. This is used by PHP function "inputButton" in order 
		  not to send a special JavaScript function through PHP only to change the 
			 form receiver.
*/

function sas(y,args) {
	var v=sas.arguments;
	var btnset=false;

	if (v.length>1) {
		for (var i=1; i<v.length; i+=2) {
			if (v[i]!='') {
				if (v[i]=='action') y.form.action=v[i+1];
				if (v[i]=='method') y.form.method=v[i+1];
				else y.form.elements[v[i]].value=v[i+1];
			}
			if (v[i]=='btn') btnset=true;
		}
	}

	if (!btnset && y.form.btn!=undefined)y.form.btn.value="";

	/* input type=image and type=submit will submit by themselves, 
		 while input type=text is a workaround for planner, IIRC */

	if (y.type!='image' && y.type!='text' && y.type!='submit') y.form.submit();
}

function enterSubmit(x,e,of,ov) {
	var keycode;
	if (window.event) keycode=window.event.keyCode;
	else if (e) keycode=e.which;
	else return true;

	if (keycode==13) {
		x.form.elements[of].value=ov;
		x.form.submit();
		return false;
	}
	else return true;
}

/* This little popup function replaces popRoom, popCar and old popInfo */

function popInfo(pid) {
  var myRnd = "pw"+((Math.random()).toString()).replace(".","");
	
	var param="toolbar=0,location=0,directories=0,status=0,resizeable=0";
	param=param+"menubar=0,scrollbars=1,width=400,height=240";
  
	pw=window.open("/partner/pop_price.php?pid="+pid,myRnd,param);
  return false;  // make sure link isn't followed
}

function popText(x) {
	var myRnd="pw"+((Math.random()).toString()).replace(".",""),realx;

	var pw=window.open("",myRnd,
										 "toolbar=no,scrollbars=yes,width=320,height=200");

	realx=unescape(x.replace(/\+/g," "));

	pw.document.write("<html><head><title>Info</title></head><body>");
	pw.document.write(realx+"</body></html>");
	return false;
}

function vote(qid,aid,height) {
  var myRnd = "pw"+((Math.random()).toString()).replace(".","");
	
	var param="toolbar=0,location=0,directories=0,status=0,resizeable=1";
	param=param+"menubar=0,scrollbars=1,width=400,height="+(110+height*18);
  
	pw=window.open("/inc/svaraomrostning.php?qid="+qid+"&aid="+aid,myRnd,param);
  return false;  // make sure link isn't followed
}

function ays(message,url,x) {
  if (window.confirm(message+"?")) {
		x.href=url;
		return true; 
	} else return false;
}

function checkagreed(x,lang) {
	if (x.avtal.checked==false) {
		switch (lang) {
		case "se":
			msg="Du måste ha läst och godkänt avtalet!";
			break;
		case "en":
		default:
			msg="You need to read and agree on the terms!";
			break;
		}
		alert(msg);
		return false;
	} else return true;
}

function updateForm(sender){
	var x = document.profileForm;
	var intVal = parseInt(sender.value);
	if(isNaN(intVal) || intVal>0){
		x.submit();
	}
}

function selectCapital(country,sess_id){
	var href="sel_capital.php?country="+country+"&sess_id="+sess_id;
	var windowName="";
	var options="toolbar=NO,screenX=50,screenY=50,width=350,height=150";
	if(!selectWindow || selectWindow.closed){
		selectWindow = window.open(href,windowName,options);
	}
	else{
		if(selectWindow.document){
			selectWindow.document.forms["selcap"].city.focus();
		}
	}
}

function processCapital(country,sess_id){
	var href="index.php?country="+country+"&sess_id="+sess_id;
	document.location.href=href;
}


function processCity(country,province,city){
	if (mainpage_sender!=null && cc!=null && prov!=null) {
		addOption(cc,country);
		addOption(prov,province);
		addOption(mainpage_sender,city);
	}
	mainpage_sender.form.submit();
}

function addCity(sender){
	var href,x="",argv=addCity.arguments,uuid=0;

	mainpage_sender=sender;
	if (argv.length>1) {
		uuid=argv[1];
		if (argv.length>2) x=argv[2]+"_";
	}
	cc=sender.form.elements[x+'country'];
	prov=sender.form.elements[x+'province'];
	href="/misc/new_city.php?country="+cc.value+"&province="+prov.value;

	if (parseInt(sender.value)==-1 && cc.value.length==2 && uuid>0) {
		window.open(href,"","toolbar=no,scrollbars=yes,width=400,height=200");
		mainpage_sender.selectedIndex = 0;
	}
	else sender.form.submit();
}

function lookupCity(sender) {
	var href,x="",argv=lookupCity.arguments,uuid=0;
	
	if (argv.length>1) {
		uuid=argv[1];
		if (argv.length>2) x=argv[2]+"_";
	}
	mainpage_sender=sender.form.elements[x+'city'];
	cc=sender.form.elements[x+'country'];
	prov=sender.form.elements[x+'province'];
	
	window.open("/misc/search_city.php","",
							"toolbar=no,scrollbars=yes,width=400,height=200");
	
	mainpage_sender.selectedIndex = 0;
}

function validateImages(x){
	var i,j=0,jend=1,jcurr=1,filename,idx=-1,errmsg="";
	var newurl,imgact,imgarr=x.elements['imgnr[]'];
	
	if (imgarr) {
		while (j<jend) {
			if (imgarr.length) {
				jend=imgarr.length;
				jcurr=imgarr[j].value;
			}
			else jcurr=imgarr.value;

			imgact=x.elements['imgact['+jcurr+']'];
			newurl=x.elements['newurl['+jcurr+']'];
			
			if (imgact.value=='repl') {
				filename=newurl.value;
				for (i=0; i<filename.length; i++) {
					if (filename.charAt(i)==".") idx=i;
				}
				if (idx==-1) return true;
				else {
					var ext = filename.substr(idx+1);
					if (ext=="jpg" || ext=="gif")return true;
					else {
						// error
						errmsg += filename + " has an unknown extention. Supported types "+
							"are gif and jpg.\n";
					}
				}
			}
			j++;
		}
	}

	if (errmsg!="") {
		alert(errmsg);
		return false;
	} else return true;
}

/* Validera e-postadress

	 var re= /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$/i;
	 if (!re.test(x.email.value)) { ... }
*/

function validate_form(obj) {
	var e = 0;
	var errms = '';
	
	for (var i = 0; i < obj.elements.length; i++) {
		var el = obj.elements[i];
		if (el.className.indexOf('check')>0 || el.className == 'check') {
					
			switch (el.type) {
			case "text":
				if((el.value).trim() == "") {
					e = 1;
					el.style.backgroundColor = '#dddddd';
					errms = 'Du har missat att fylla i en del obligatoriska fält. Dessa har markerats.\n';
				}  else {
					el.style.backgroundColor = '#ffffff';
				}
				break;
				
			case "checkbox":
				if (!el.checked) {
					e=1;
					errms=errms+'Du har glömt att kryssa i rutan för hantering av personuppgifter.\n';
				}
			}
		}
	}
	
	if(e == 1) {
		alert(errms);
		return false;
	}
	else {
		return true;
	}
}

/* dålig lösning för att få lokaliserade javascripts */

function validate_form_en(obj) {
	var e = 0;
	var errms = '';
	
	for (var i = 0; i < obj.elements.length; i++) {
		var el = obj.elements[i];
		if (el.className.indexOf('check')>0 || el.className == 'check') {
					
			switch (el.type) {
			case "text":
				if(el.value == "") {
					e = 1;
					el.style.backgroundColor = '#dddddd';
					errms = 'You have forgotten to fill in a few required fields. These have been highlighted.\n';
				}  else {
					el.style.backgroundColor = '#ffffff';
				}
				break;
				
			case "checkbox":
				if (!el.checked) {
					e=1;
					errms=errms+'You have forgotten to check the box for handling personal details.\n';
				}
			}
		}
	}
	
	if(e == 1) {
		alert(errms);
		return false;
	}
	else {
		return true;
	}
}



function disableField(x,y) {
	var cmp,action,v=disableField.arguments,f=document.getElementById(y);

	cmp=(v.length>2 ? v[2] : 0);
	action=(v.length>3 ? v[3] : "");

  if (x.value!=cmp) {
    f.value = "";
    f.disabled = true;
		f.style.visibility='hidden';
		if (action=="reload" && x.value!=0) x.form.submit();
  }
  else {
		f.disabled = false;
		f.style.visibility='visible';
	}
}

function disableMultiField(x,args) {
	var i,vis,e,v=disableMultiField.arguments;

	vis=(x.value!=v[1] ? "hidden" : "visible");

	for (i=2; i<v.length; i++) {
		e=v[i];
		if (e.type==undefined) e=document.getElementById(e);
		else {
			if (x.value!=v[1]) {
				e.disabled=true;
				e.value="";
			}
			else e.disabled=false;
		}
		e.style.visibility=vis;
	}
}

function addOption(ele,val) {
	var i=Member(ele.options,val);
	if (i==ele.length) {
		ele.options[ele.length] = new Option("",val,true,true);
		ele.selectedIndex=ele.length-1;
	} else ele.selectedIndex=i;
}

function ArrMember(arr,str) {
	var found=false,i=-1;
	while (!found && ++i<arr.length) found=(arr[i]==str);
	return i;
}

function Member(arr,str) {
	var found=false,i=-1;
	while (!found && ++i<arr.length) found=(arr[i].value==str);
	return i;
}

/* y is a predicate (true or false), while o is a colour string */
function setColandOK(y,o) {
  col = (y ? "#ff0000" : o);
  ok = ok && !y;
}

function adjustD(m,d) {
	var tmpd=parseInt(d.value),tmpm=parseInt(m.value)-1;

	if (tmpm>=0 && tmpd>0) {
		while ((new Date(2000,tmpm,tmpd)).getMonth()!=tmpm) tmpd--;
		d.selectedIndex -= (parseInt(d.value) - tmpd);
	}
}

function fixDate(month,day,year,numdays) {
	var tmpd=parseInt(day.value),tmpm=month.value-1,newdate,olddate,nd;

	var stday=document.getElementById("stday");
	var retdate=document.getElementById("retdate");
	var nights=document.getElementById("nights");

	var monthname=Array("January","February","March","April","May","June","July",
											"August","September","October","November","December");

	var dayname=Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");

	while ((olddate=new Date(year.value,tmpm,tmpd)).getMonth()!=tmpm) tmpd--;
	day.selectedIndex -= (parseInt(day.value) - tmpd);

	if (numdays!=null) {
		nd=parseInt(numdays.value);
		if (isNaN(nd) || nd==0) nd=1;
		
		if (nd>366) {
			nd=366;
			alert("You can only plan your trip for one year (365 nights).");
		}
		numdays.value=nd;
	}

	if (nights!=null)nights.innerHTML=--nd;
	if (stday!=null) stday.innerHTML=dayname[olddate.getDay()];

	if (retdate!=null) {
		newdate=new Date(year.value,tmpm,tmpd+nd);
		
		retdate.innerHTML=monthname[newdate.getMonth()]+" "+newdate.getDate()+", "+newdate.getFullYear()+" ("+dayname[newdate.getDay()]+")";
	}
}

function toggleWeekdays(x) {
	var i,y=x.form.elements['weekdays[]'];

	switch (x.value) {
	case 'Daily':
		for (i=0; i<y.length-1; i++) y[i].checked=x.checked;
		break;
	default:
		y[y.length-1].checked=false;
		break;
	}
}

function toggleDates(x) {
	var y=x.form;
	y.frm.disabled=y.frd.disabled=y.tom.disabled=y.tod.disabled=x.checked;
}

function toggleTime(tc,h,m) {
	h.selectedIndex=(tc.checked ? 1 : 0);
	m.selectedIndex=(tc.checked ? 1 : 0);
	h.disabled=m.disabled=!tc.checked;
}

/* toggleH is used in Planner step 3 etc */
function toggleH(x,e) {
	var l=x.form.elements[e];

	l.value = (l.value!="" ? "" : "on");
	x.form.submit();
}

function setDD(sel,idx) {
	var j=0;
	while (j<sel.options.length) {
		if (sel.options[j].value == idx) sel.selectedIndex=j;
		j++;
	}
}

function setValids(x) {
	var frh = document.arc.frh, fri = document.arc.fri;
	var toh = document.arc.toh, toi = document.arc.toi;
	var frm = document.arc.frm, frd = document.arc.frd;
	var tom = document.arc.tom, tod = document.arc.tod;
	var frc = document.arc.frc, toc = document.arc.toc;
	
	var i=0, found=false, fm;
	
	disableField(x,document.arc.widother);
	
	while (i<season.length && !found) {
		if (season[i][0]==x.value) {
			setDD(frm,season[i][2]);
			setDD(frd,season[i][3]);
			setDD(tom,season[i][4]);
			setDD(tod,season[i][5]);
			frc.checked=(season[i][6]!="");
			toc.checked=(season[i][8]!="");
			toggleTime(frc,frh,fri);
			toggleTime(toc,toh,toi);
			
			if (season[i][6]!="") {
				setDD(frh,season[i][6]);
				setDD(fri,season[i][7]);
			}
			
			if (season[i][8]!="") {
				setDD(toh,season[i][8]);
				setDD(toi,season[i][9]);
			}
			found=true;
		}
		else i++;
	}
	
	if (!found) { // if there was no presets, disable all time
		frc.checked=toc.checked=false;
		toggleTime(frc,frh,fri);
		toggleTime(toc,toh,toi);
	}
}

function showYULA(){
	window.open("/inc/anv-avtal.html","",
							"scrollbars=yes,screenX=50,screenY=50,width=600");
	return false;
}

function urlspace(str) {
	return (((str.toString()).replace(/ /g,"+")).
					replace(/&/g,"%26")).replace(/\?/g,"%3f");
}

function sendMessage(uuid,senderid) {
	var v=sendMessage.arguments,href="/member/post_message.php?uuid="+uuid;
	
	/* fall-through! */
	switch (v.length) {
	case 7:
		href+="&murldesc="+urlspace(v[6]);
	case 6:
		href+="&murl="+urlspace(v[5]);
	case 5:
		href+="&body="+urlspace(v[4]);
	case 4:
		href+="&read="+urlspace(v[3]);
	case 3:
		href+="&subject="+urlspace(v[2]);
	}
	
  /* alert(href); */

	/*if (senderid!=0) { *(/
		/* width=404, height=344 */

	window.open(href,"",
							"scrollbars=no,screenX=50,screenY=50,width=400,height=450");
	/* } else alert("You have to be logged in to send a message."); */
}

function addFriend(uuid,username){
	var href="/member/add_friend.php?uuid="+uuid;

	if (window.confirm("Do you wish to be a friend to "+username+"?")) {
		window.open(href,"","scrollbars=no,screenX=50,screenY=50,width=300,height=100");
	}
}

function popupSurvey(){
	window.open("/survey.php","","scrollbars=no,screenX=50,screenY=50,width=400,height=220");
}

function cancelForm(url){
	if( url ){
		document.location.href = url;
	}
}

function fakeHover(obj,event) {
	/*
		Mozilla 1.4 and Opera 7 uses document.defaultView.getComputedStyle
		while MSIE 6 uses obj.currentStyle. Not sure about the rest.
	*/

	var cstyle;

	switch (event) {
	case 'over':
		if (obj.currentStyle !== undefined) {
			obj.prevcolor=obj.currentStyle.color;
			obj.prevweight=obj.currentStyle.fontWeight;
		}
		else {
			cstyle=document.defaultView.getComputedStyle(obj,'');
			obj.prevcolor=cstyle.getPropertyValue("color");
			obj.prevweight=cstyle.getPropertyValue("fontWeight");
		}
		obj.style.color="#000000";
		obj.style.fontWeight="bold";
		break;
	case 'out':
		if (obj.prevcolor) obj.style.color=obj.prevcolor;
		if (obj.prevweight) obj.style.fontWeight=obj.prevweight; 
		break;
	}
}

function myFileBrowser (field_name, url, type, win) {

	tinyMCE.activeEditor.windowManager.open({
    file : "/upload.php?type=" + type + "&url=" + url,
    width: 574,
    height: 273,
    resizable: "yes",
    inline : "yes",
    close_previous: "no"
},{
    window: win,
    input: field_name
  });
	return false;
}


function DNS(x) {
	var dns1=document.getElementById("dns");
	var dns2=document.getElementById("dns2");

	dns1.style.visibility=(x==0 ? "hidden" : "visible");
	dns2.style.visibility=(x==0 ? "hidden" : "visible");
}

function popDNS(dns,tld) {
  var myRnd = "pw"+((Math.random()).toString()).replace(".","");

	var param="toolbar=0,location=0,directories=0,status=0,resizeable=0";
	param=param+",menubar=0,scrollbars=1,width=300,height=200";

	window.open("/dns/index.php?dns="+dns+"&tld="+tld,myRnd,param);
	return false;
}

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }
