// JavaScript Document
function GetXmlHttpObject()
{
  var xmlHttp=null;
  try
    {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    }
  catch (e)
    {
    // Internet Explorer
    try
      {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
    catch (e)
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    }
  return xmlHttp;
}

function initialiseGetData() {
	GET_DATA = new Array();
	var getDataString = new String(window.location);
	var questionMarkLocation = getDataString.search(/\?/);
	if (questionMarkLocation != -1) {
		getDataString = getDataString.substr(questionMarkLocation+1);
		var getDataArray = getDataString.split(/&/g);
		for (var i=0;i<getDataArray.length;i++) {
			var nameValuePair=getDataArray[i].split(/=/);
			GET_DATA[unescape(nameValuePair[0])] = unescape(nameValuePair[1]);
		}
	}
}
 
function setCookie(c_name,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name) {
	if (document.cookie.length>0)   {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1) { 
			c_start=c_start + c_name.length+1; 
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
    		return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}
 
function LTrim(str) {
	var whitespace = new String(" tnr");
	var s = new String(str);
	if (whitespace.indexOf(s.charAt(0)) != -1) {
		var j=0, i = s.length;
		while (j < i && whitespace.indexOf(s.charAt(j)) != -1) {
			j++;
		}
		s = s.substring(j, i);
	}
	return s;
}
 
function RTrim(str) {
	var whitespace = new String(" tnr");
	var s = new String(str);

	if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
		var i = s.length - 1;
		while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1) {
			i--;
		}
		s = s.substring(0, i+1);
	}
	return s;
}
 
function Trim(str) {
	return RTrim(LTrim(str));
}

function mouseCoords(ev){
	if(ev.pageX || ev.pageY){
		return {x:ev.pageX, y:ev.pageY};
	}
	if (typeof(document.documentElement.scrollLeft)=='number') {
		return {
			x:ev.clientX + document.documentElement.scrollLeft - document.documentElement.clientLeft,
			y:ev.clientY + document.documentElement.scrollTop - document.documentElement.clientTop
		};
	} else {
		return {
			x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
			y:ev.clientY + document.body.scrollTop - document.body.clientTop
		};
	}
}

function isValidEmail(email) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	return (reg.test(email));
}

function goSearch(keyword) {
	window.location = "search.php?key="+encodeURIComponent(keyword);
}

function showMoreFilters() {
	var vis;
	if ($(this).attr('show')=="")
		vis = $(this).attr('show')=="true";
	else
		vis = true;
	if (vis)
		$('#moreFilters').show('fast');
	else
		$('#moreFilters').hide('fast');
		$('#filName').hide('fast');
	$(this).attr('show',!vis);
}

function showMoreCities() {
	var vis;
	if ($(this).attr('show')=="")
		vis = $(this).attr('show')=="true";
	else
		vis = true;
	if (vis)
		$('#moreCities').show('fast');
	else
		$('#moreCities').hide('fast');
	$(this).attr('show',!vis);
}

$(document).ready(function() {
	adSystem();	
	$(	'<div id="shareEmail">'+
		'<table border="0">'+
		'<tr><td>your name:</td><td><input type="text" class="inputText" name="yourname" /></td></tr> '+
		'<tr><td>friend\'s name:</td><td><input type="text" class="inputText" name="friendname" /></td></tr> '+
		'<tr><td>friend\'s email:</td><td><input type="text" class="inputText" name="friendemail" /></td></tr> '+
		'<tr><td colspan="2" align="right"><input name="btnSend" type="button" value="send" class="inputText" onclick="sendToFriend()" /> '+
		'<input type="hidden" name="url" /><input type="hidden" name="eventID" />'+
		'<input type="button" value="cancel" class="inputText" onclick="$(\'#shareEmail\').hide()" />'+
		'<div id="shareEmailMsg"></div></td></tr>'+
		'</table>'+
		'</div>').appendTo(document.body);
	if ($('#iconShareFriend')) {
		$('#iconShareFriend').click(function (e) {
			sharePageToFriend($(this).attr('url'), $(this).attr('eventID'), e);
		});
	}
	$('#filName').hide('fast');
});

function adSystem() {
	adSrc(1);
	adSrc(2);
	adSrc(3);
}

function adSrc(typ) {
	var objs, css, imgWidth, adsenseContainerID;
	switch (typ) {
		case 1:
			objs = $('div[grp=adTop]');
			css = "";
			imgWidth = "880";
			adsenseContainerID = "adSenseTop";
			break;
		case 2:
			objs = $('div[grp=adContent]');
			css = "style=\"padding: 15px;\"";
			imgWidth = "780";
			adsenseContainerID = "adSenseMid";
			break;
		case 3:
			objs = $('div[grp=adRight]');
			css = "style=\"padding-top: 15px; width: 125px\"";
			imgWidth = "125";
			adsenseContainerID = "adSenseRig";
			break;
	}
	if (!objs.length) return;
	var num = objs.length;
	var i=0;
	var cid=0;
	var hasQueryString = document.URL.indexOf('catID');
	if(hasQueryString>0){
		var strQueryString = document.URL.substring(hasQueryString+6, document.URL.length);
		var cityStr = strQueryString.indexOf('&');
		if(cityStr<0){
			cityStr=strQueryString.length;
			}
		cid = strQueryString.substring(0, cityStr);
		}
	$.ajax({
		type: "POST",
		url: "process.php",
		data: "pid=40&type="+typ+"&num="+num+"&cid="+cid,
		success: function (xml) {
			var ad, title, adSrc, adID;
			$(xml).find("ad").each(function(id) {
				ad = $("ad", xml).get(id);
				adID = $("adID", ad).text();
				title = $("title", ad).text();
				adSrc = $("adSrc", ad).text();
				if (title!='googleAdsense') {
//					$('#'+adsenseContainerID).hide();
					if (objs[i]) {
						$(objs[i]).show();
						if(title=="newsletter"){
							$(objs[i]).html("<img style=\"cursor:pointer\" src=\""+adSrc+"\" alt=\""+title+"\" "+css+" onclick=\"subscribeDialog();\"/>");
							}
						else{
							$(objs[i]).html("<a target=\"_blank\" href=\"redirect.php?type=3&id="+adID+"\" border=\"0\"><img src=\""+adSrc+"\" alt=\""+title+"\" "+css+" /></a>");
							}
					}
				} else {
					if ($('#'+adsenseContainerID)) {
//						$(objs[i]).hide();
//						$('#'+adsenseContainerID).show();
					}
				}
				i++;
			});
		}
	});
	setTimeout("adSrc("+typ+")", 8000);
}

function sharePageToFriend(url, eventID, e) {
	$('#shareEmail').css('left',e.pageX).css('top',e.pageY-100).show('fast');
	$('#shareEmail input[name=url]').val(url);
	$('#shareEmail input[name=eventID]').val(eventID);
	setTimeout("$('#shareEmail input:visible:enabled:first').focus();", 300);
}

function sendToFriend() {
	$('#shareEmail input[name=btnSend]').attr('disabled',true);
	var yourname = $('#shareEmail input[name=yourname]').val();
	var friendname = $('#shareEmail input[name=friendname]').val();
	var friendemail = $('#shareEmail input[name=friendemail]').val();
	var url = $('#shareEmail input[name=url]').val();
	var eventID = $('#shareEmail input[name=eventID]').val();
	if (yourname==""||friendname==""||(!isValidEmail(friendemail))) {
		alert("Please enter all the fields and check the email correctness.");
		return false; 
	}
	
	yourname = encodeURIComponent(yourname);
	friendname = encodeURIComponent(friendname);
	friendemail = encodeURIComponent(friendemail);
	url = encodeURIComponent(url);
	eventID = encodeURIComponent(eventID);
	$.ajax({
		type: "POST",
		url: "process.php",
		data: "pid=48&yourname="+yourname+"&friendname="+friendname+"&friendemail="+friendemail+"&url="+url+"&eventID="+eventID,
		success: function (txt) {
			$('#shareEmailMsg').html('Email sent!');
			setTimeout("$('#shareEmail').hide('slow');$('#shareEmail input[name=btnSend]').attr('disabled',false);$('#shareEmailMsg').html('')",2000);
			return;
		}
	});
}

function subs_validation(arg) {
	var rtn = true;
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	$('form input[type=text], form textarea, form select').each( function () {
		if ($(this).attr('id')=='email' || $(this).attr('name')=='email' || $(this).attr('id')=='visitorEmail' ) {
			rtn = rtn && reg.test($(this).val());
			if (!rtn) $('#subscribeBox #msg').html('Please check your email address, and correct it.');//subs_err('Please check your email address, and correct it.');
		}
	});
	return rtn;	
}

function subscribeDialog(arg) {
	if (!$('#subscribeBox').html()) {
	$(	'<div id="subscribeBox" name="subscribeBox" title="Subscribe to our newsletter">'+
		'<form onSubmit="return false;">'+
		'<table border="0" cellspacing="1" >'+
/* 		'	<tr><td align="right">your name: </td>'+
		'		<td><input type="text" id="name" name="name" class="inputTextSubs" size="50" /></td>'+
		'	</tr>'+ */
		'<tr><td style="border-bottom:2px solid #AAAAAA;" colspan="2">'+
			'<div><font class="darker_grey16">news</font><font class="dark_grey16">letter</font></div></td></tr>'+
		'<tr><td align="left" colspan="2" style="padding-bottom: 15px;"><font class="blue11"><br />Subscribe to receive the latest information<br />on art events in the week ahead<br/></font></td></tr>'+
		'	<tr>'+
		'		<td width=80><font class="blue12">your email:</font></td>'+
		'		<td><input type="text" id="email" name="email" style="font-family: Helvetica;font-size: 11px;border: solid 1px #AAAAAA;width: 150px;" align="center" valign="center" size="50" value=""/></td>'+//class="inputTextSubs"
		'	</tr><tr>'+
		'		<td align="right" colspan="2">'+
		'		<input id="subscribeButton" name="subscribeButton" class="button" type="submit" value="Submit" />'+
		'		</td>'+
		'	</tr><tr id="msgrow">'+
		'		<td colspan="2"><span id="msg" style="color: #FF6600">&nbsp;</span></td>'+
		'	</tr>'+
		'</table></form></div>').appendTo(document.body);
		$('#subscribeButton').click(function () {
			//Owing to some problems, the validation here is only check the email is correct. And process.php will check whether the name is empty
			if($('#subscribeBox').height<240){
			$('#subscribeBox').height($('#subscribeBox').height()+20);}
			if(subs_validation(arg)){
			subscribe(arg);}
			return false;
		});
		$('#subscribeBox').dialog({
			width: 268,
			height: 230,
			maxHeight: 240,
			minHeight: 230,
			resizable: false,
			modal: true
		});
	} else {
		$('#subscribeBox').dialog("open");
	}
	$('#subscribeBox #email').focus();
}

function subscribe(arg) {
	var p = encodeURIComponent($('#subscribeBox #email').val());
	$.ajax({
		type: "POST",
		url: "process.php",
		data: "pid=66&email="+p,
		success: function (txt) {
			if (txt=='1') {
				if (arg==null) {
					$('#subscribeBox #msg').html('Thank you, newsletter will be sent every sunday');
					setTimeout( "$('#subscribeBox #msg').html('');$('#subscribeBox').dialog('close');", 4000 );
				} else {
					if (arg.action=="comment")
						commentDialog(arg.id_type, arg.vid);
				}
			}
			else {
				$('#subscribeBox #msg').html('Your email had been subscribed before');
			}
		}
	});
}

function registerDialog(arg) {
	if (!$('#registerBox').html()) {
	$(	'<div id="registerBox" title="Register to artinasia.com">'+
		'<form onSubmit="return false;">'+
		'<table border="0" cellpadding="2" cellspacing="2">'+
		'	<tr><td align="right"><font color="Black">loginname: </font></td>'+
		'		<td><input class="inputText" type="text" id="loginname" name="loginname" /></td>'+
		'	</tr>'+
		'	<tr>'+
		'		<td align="right"><font color="Black">password: </font></td>'+
		'		<td><input class="inputText" type="password" id="password" name="password" /></td>'+
		'	</tr>'+
		'	<tr>'+
		'		<td colspan="2"><span id="msg" style="color: #FF6600">&nbsp;</span></td>'+
		'	</tr>'+
		'	<tr>'+
		'		<td colspan="2" align="right">'+
		'			<a href=\"visitorRegister.php\">visitor registration</a>'+
		'			<input id="loginSubmitButton" class="button" type="submit" value="Submit" />'+
		'		</td>'+
		'	</tr>'+
		'</table></form></div>').appendTo(document.body);
		$('#loginSubmitButton').click(function () {
			register(arg);
			return false;
		});
		$('#registerBox').dialog({
			width: 260,
			height: 165,
			maxHeight: 165,
			minHeight: 165,
			resizable: false,
			modal: true
		});
	} else {
		$('#registerBox').dialog("open");
	}
	$('#registerBox #loginname').focus();
}

function register(arg) {
	var n = encodeURIComponent($('#registerBox #loginname').val());
	var p = encodeURIComponent($('#registerBox #password').val());

	$.ajax({
		type: "POST",
		url: "process.php",
		data: "pid=2&name="+n+"&pass="+p,
		success: function (txt) {
			if (txt=='1') {
				if (arg==null) {
					window.location.reload();
				} else {
					if (arg.action=="comment")
						commentDialog(arg.id_type, arg.vid);
				}
			} else {
				$('#registerBox #msg').html('Incorrect username / password pair');
			}
		}
	});
}

function loginDialog(arg) {
	if (!$('#loginBox').html()) {
	$(	'<div id="loginBox" title="login">'+
		'<form onSubmit="return false;">'+
		'<table border="0" cellpadding="2" cellspacing="2">'+
		'	<tr><td align="right"><font class="blue11">username: </font></td>'+
		'		<td><input style="font-family: Helvetica;font-size: 11px;border: solid 1px #AAAAAA;" type="text" id="loginname" name="loginname" /></td>'+
		'	</tr>'+
		'	<tr>'+
		'		<td align="right"><font class="blue11">password: </font></td>'+
		'		<td><input style="font-family: Helvetica;font-size: 11px;border: solid 1px #AAAAAA;" type="password" id="password" name="password" /></td>'+//class="inputText"
		'	</tr>'+
		'	<tr>'+
		'		<td colspan="2"><span id="msg" style="color: #FF6600">&nbsp;</span></td>'+
		'	</tr>'+
		'	<tr>'+
		'		<td colspan="2" align="right">'+
		'			<!-- <a href=\"visitorRegister.php\">visitor registration</a> &nbsp; &nbsp; -->'+
		'			<input id="loginSubmitButton" class="button" type="submit" value="Submit" />'+
		'		</td>'+
		'	</tr>'+
		'</table></form></div>').appendTo(document.body);
		$('#loginSubmitButton').click(function () {
			login(arg);
			return false;
		});
		$('#loginBox').dialog({
			width: 260,
			height: 165,
			maxHeight: 165,
			minHeight: 165,
			resizable: false,
			modal: true
		});
	} else {
		$('#loginBox').dialog("open");
	}
	$('#loginBox #loginname').focus();
}

function login(arg) {
	var n = encodeURIComponent($('#loginBox #loginname').val());
	var p = encodeURIComponent($('#loginBox #password').val());

	$.ajax({
		type: "POST",
		url: "process.php",
		data: "pid=2&name="+n+"&pass="+p,
		success: function (txt) {
			if (txt=='1') {
				if (arg==null) {
					window.location.reload();
				} else {
					if (arg.action=="comment")
						commentDialog(arg.id_type, arg.vid);
				}
			} else {
				$('#loginBox #msg').html('Incorrect username / password');
			}
		}
	});
}

function comment_click(idType, id) {
	$.ajax({
		type: "POST",
		url: "process.php",
		data: "pid=49",
		success: function (txt) {
			if (txt=="-1") {
				// plusSize="";
				// var agt=navigator.userAgent.toLowerCase();
				// if (agt.indexOf("safari") != -1 || agt.indexOf("chrome") != -1) plusSize=' style="font-size: 10px;"';
				visitorStr=
				'<table>'+
				'	<tr>'+
				'		<td class="blue11">Name: </td>'+
				'		<td><input style="font-family: Helvetica;font-size: 11px;border: solid 1px #AAAAAA;" type="text" id="visitorName" name="visitorName" /></td>'+
				'		<td class="dgrey11">(required)</td>'+
				//'		<td class="dgrey11"'+plusSize+'>subscribes to comments</td>'+
				//'		<td><input style="font-family: Helvetica;font-size: 11px;border: solid 1px #AAAAAA;" type="checkbox" id="subscribeCom" name="subscribeCom" checked/></td>'+
				'	</tr>'+
				'	<tr>'+
				'		<td class="blue11">Email: </td>'+
				'		<td><input style="font-family: Helvetica;font-size: 11px;border: solid 1px #AAAAAA;" type="text" id="visitorEmail" name="visitorEmail" /></td>'+
				'		<td class="dgrey11">(will not be published)(required)</td>'+
				'	</tr>'+
				'</table>';
				commentDialog(idType, id, visitorStr);
			}
			else {
				commentDialog(idType, id, "");
			}
		}
	});
}

function commentDialog(idType, id, visitorStr) {
	var subcribeStr="";
	if(visitorStr!=""){
		subcribeStr=
		'	<span class="dgrey11">subscribes to newsletters</span>'+
		'	<input style="font-family: Helvetica;font-size: 11px;border: solid 1px #AAAAAA;" type="checkbox" id="subscribeNews" name="subscribeNews" checked/>';
		}
	if (!$('#commentBox').html()) {
	$(	'<div id="commentBox" title="comment">'+
		'<form onsubmit="return false;" style="padding: 0; margin: 0">'+visitorStr+
		'	<textarea class="inputText" type="text" name="comment" style="width: 320px; height: 120px; resizable:false;" /></textarea>'+
		'	<table border="0">'+
		'	<tr>'+
		'		<td valign="bottom" class="blue11">Verification Code: </td>'+
		'		<td><img src="getRandImg.php" border="0" /></td>'+
		'		<td valign="bottom"><input class="inputText" size="5" name="vCode" /></td>'+
		'	</tr>'+
		'	</table>'+
		'	<div id="commentMsg" style="color: #FF6600">&nbsp;</div>'+
		'	<table width="100%">'+
		'	<tr><td colspan="3" align="right">'+
		subcribeStr+
		'	<input id="submitButton" name="submitButton" class="button" type="submit" value="Submit" onclick="postComment('+idType+','+id+');return false;" />'+
		'	</td></tr>'+
		'	</table>'+
		'</form>'+
		'</div>').appendTo(document.body);
		$('#submitButton').click(function () {
			//Owing to some problems, the validation here is only check the email is correct. And process.php will check whether the name is empty
			if(!subs_validation($('#visitorEmail'))){
				$('#commentBox #commentMsg').html('invalid email address');
			}
		});
		var plusLenght = 0;
		var agt=navigator.userAgent.toLowerCase();
		if (agt.indexOf("safari") != -1 || agt.indexOf("chrome") != -1) plusLenght=8;
		if(visitorStr==""){
			$('#commentBox').dialog({
			resizable: false,
			modal: true,
			width: 350+plusLenght,
			height: 245+plusLenght,
			maxHeight: 245+plusLenght,
			minHeight: 245+plusLenght
			});
			}
		else{
			$('#commentBox').dialog({
			resizable: false,
			modal: true,
			width: 350+plusLenght,
			height: 310+plusLenght,
			maxHeight: 310+plusLenght,
			minHeight: 310+plusLenght
			});
			}
	} else {
		$('#commentBox').dialog("open");
	}
	$('#commentBox textarea').focus();
}

function postComment(idType, id) {
	var content = encodeURIComponent($('#commentBox textarea').val());
	var vCode = encodeURIComponent($('#commentBox input[name=vCode]').val());
	var name = encodeURIComponent($('#commentBox input[name=visitorName]').val());
	var email = encodeURIComponent($('#commentBox input[name=visitorEmail]').val());
	var scom = encodeURIComponent($('#commentBox input[name=subscribeCom]').val());
	var snews = encodeURIComponent($('#commentBox input[name=subscribeNews]').val());
	if (content=="") {
		$('#commentBox #commentMsg').html('Please enter your comment above.');
		return;
	}
	$.ajax({
		type: "POST",
		url: "process.php",
		data: "pid=50&idType="+idType+"&id="+id+"&content="+content+"&vCode="+vCode+"&name="+name+"&email="+email+"&scom="+scom+"&snews="+snews,
		success: function (txt) {
			if (txt=='1')
				window.location.reload();
			else if (txt=='-1')
				$('#commentBox #commentMsg').html('incorrect verify code');
			else if (txt=='-2')
				$('#commentBox #commentMsg').html('invalid email address');
			else {
				$('#commentBox #commentMsg').html('Unexpected error, please submit later ...');
			}
		}
	});
}