var url = "/functions?"; // The server-side script 
var dividtoreplace = "";
var divreplaceeffect = "";
var div_Number = 0;
var success_event_handler_weffect = null;
var isAutoCompleteOpened = false;
var alert_ad_hide_flag = true;
var is_edit_alert = false;

function handleHttpResponse() {    
        if (http.readyState == 4) { 
              if(http.status==200) {
	        var results=http.responseText;
		var prefix=results.substring(0,7);
		if(prefix=="Invalid")
		{ 
			document.getElementById('loading').innerHTML = "<font color='red'>Invalid LoginID or Password</font>";
		}
		else
		{
			//window.location=url+results;
			window.location=results;
		}
              } 

              } 

        } 


function sendpassword()
{
if(!V2validateData("req",document.passwordform.email,"Please enter your email address"))
	return;
if(!V2validateData("email",document.passwordform.email,"Enter valid email address"))
	return;
	
document.passwordform.method="POST"
document.passwordform.action=url+"action=sendpassword";
document.passwordform.submit()
}

function changeaccountsettings(buttonPressed)
{
if(buttonPressed.value=="Change password")
{
	if(document.accountupdateform.currpass.value == "")
	{
		alert("Please write your current Password");
		return;
	}
	if(document.accountupdateform.newpass.value == "")
	{
		alert("Please write your new Password");
		return;	
	}
	if(document.accountupdateform.renewpass.value == "")
	{
		alert("Please retype your new Password");
		return;	
	}
	if(document.accountupdateform.newpass.value != document.accountupdateform.renewpass.value)
	{
		alert("New password and Retype new password doesn't match");
		return;
	}
	/*display login processing status here*/
	document.accountupdateform.method="POST"
	document.accountupdateform.action=url+"action=changepassword";
	document.accountupdateform.submit()
}
else if(buttonPressed.value=="Save Alerts Settings")
{
	document.accountupdateform.method="POST"
	document.accountupdateform.action=url+"action=changeuseralertsettings";
	document.accountupdateform.submit()
}
}

/*function used for login*/
function login()
{
var id = document.getElementById("uname");
var pw = document.getElementById("upassword");
var rememberme = document.getElementById("urememberme").checked;

if(!V2validateData("req",id,"Please enter your email address"))
	return;
if(!V2validateData("email",id,"Enter valid email address"))
	return;

	if(id.value == "")
	{
		alert("Please write your login ID");
		return;
	}
	if(pw.value == "")
	{
		alert("Please write your Password");
		return;	
	}
		var user = id.value;
		var pass = pw.value;
		var red = document.getElementById("redirect").value;
	/*display login processing status here*/
	document.getElementById('loading').innerHTML = "Processing please wait...";
	http.open("GET", url + "action=login;"+escape(user)+";"+escape(pass)+";"+escape(red)+";"+escape(rememberme), true);
	http.onreadystatechange = handleHttpResponse;
	http.send(null)
}

function keyPressedLogin(keyEvent)
{
	keyEvent = (keyEvent) ? keyEvent : window.event;
	input = (keyEvent.target) ? keyEvent.target : keyEvent.srcElement;
	if(keyEvent.keyCode == 13) /*Enter code*/
	{
		login(); /*calling the same function*/
	}
}



/*function for handling response from server for support request*/
function handleContactHttpResponse()
{
	if (http.readyState == 4) { 
              if(http.status==200) {
	        var results=http.responseText;
			if(results == "Invalid")
			{
			    document.getElementById('processing_contact').innerHTML = "<font color='red'>Wrong security code provided</font>";
			}
			else
				document.getElementById('innerpage').innerHTML = results;
        } 
	      } 
}

/*function used for sending support Request*/
function sendsupportRequest()
{
		if(!V2validateData("req",document.contactForm.uname,"Please enter your Name"))
			return false;
		if(!V2validateData("req",document.contactForm.uemail,"Please enter your email address"))
			return false;
		if(!V2validateData("email",document.contactForm.uemail,"Enter valid value for Email"))
			return false;
		if(!V2validateData("numeric",document.contactForm.umobile,"Please enter only 0-9 for Mobile Number"))
			return false;
		if(!V2validateData("minlen=10",document.contactForm.udescription,"Please write atleast 10 characters to describe your problem"))
			return false;
		if(!V2validateData("minlen=5",document.contactForm.usec,"Please write complete 5 digit security code"))
			return false;
		/*display processing status here*/
		var name = encodeURIComponent(document.contactForm.uname.value);
		var email = encodeURIComponent(document.contactForm.uemail.value);
		var mobile = encodeURIComponent(document.contactForm.umobile.value);
		var reason = encodeURIComponent(document.contactForm.ureason[document.contactForm.ureason.selectedIndex].value);
		var description = encodeURIComponent(document.contactForm.udescription.value);
		var seccode = encodeURIComponent(document.contactForm.usec.value);
		document.getElementById('processing_contact').innerHTML = "<font color='red'>Processing please wait...</font>";
		http.open("GET", url + "action=contact;"+name+";"+email+";"+mobile+";"+reason+";"+description+";"+seccode, true);
		http.onreadystatechange = handleContactHttpResponse; /*Callback function for handling httpResponse*/
		http.send(null)
		return false;
}

/*Function used for adding SMS*/
function sendsmsaddRequest()
{
		if(!V2validateData("dontselect=0",document.addsmsform.smscat,"Please select a catagory"))
			return false;
		if(!V2validateData("minlen=3",document.addsmsform.smstoadd,"Please write some text for SMS"))
			return false;
		if(!V2validateData("maxlen=500",document.addsmsform.smstoadd,"Your SMS length has exceed the maximum limit"))
			return false;
		if(!V2validateData("minlen=5",document.addsmsform.usec,"Please write complete 5 digit security code"))
			return false;

		/*display processing status here*/
		document.getElementById('processing_addsms').innerHTML = "<font color='red'><img src=\"/images/loading.gif\">&nbsp;Processing please wait...</font>";
		http.open("GET", url + "action=addsms;"+document.addsmsform.smscat[document.addsmsform.smscat.selectedIndex].value+";"+encodeURIComponent(document.addsmsform.smstoadd.value)+";"+document.addsmsform.usec.value, true);
		http.onreadystatechange = handleSMSHttpResponse; /*Callback function for handling httpResponse, for both Contact form and SMS add request*/
		http.send(null);
		return false;
}

/*function for handling response from server for add SMS request*/
function handleSMSHttpResponse()
{
	if (http.readyState == 4) 
	{ 
              if(http.status==200) {
	        var results=http.responseText;
			if(results == "Invalid")
			{
			    document.getElementById('processing_addsms').innerHTML = "<font color='red'>Wrong security code provided</font>";
			}
			else
				document.getElementById('smsPage').innerHTML = results;
	        } 
	} 
}


function getHTTPObject() 
{ 
  var xmlhttp; 
  if(window.XMLHttpRequest)
  { 
    xmlhttp = new XMLHttpRequest(); 
  } 
  else if (window.ActiveXObject)
  { 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    if (!xmlhttp)
	{ 
      xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); 
    } 
}
  return xmlhttp; 
} 



function displayloginform(redirect)
{
	document.getElementById('loading').innerHTML = "<form name=\"loginform\"><input type=\"hidden\" name=\"redirect\" value=\""+redirect+"\"><font face=\"Arial\">Login:</font><input type=\"text\" name=\"uname\" size=\"15\" maxlength=\"80\" >&nbsp<font face=\"Arial\">Password:</font><input type=\"password\" name=\"upassword\" size=\"15\" maxlength=\"12\"><button name=\"B1\" onclick=\"login()\">Login</button></form>"; 
}



function displaywelcomemessage(name,lastlogin)
{
  document.getElementById('loading').innerHTML = "Welcome "+name;
}



function logout()
{
	window.location = url+"action=logout";
}

function showprofileclicked()
{
	if(document.userprofileform.ushowprofile.checked == true)
		alert("If you click on hide your profile, other people will not be able to search and contact you, so we highly recommend to uncheck this option");
}

/*Generic Ajax function to replace some div from some HTML text received from server
The processing icon is shown in same div which will be replaced from contents from server
*/
function sendAjaxCall(strswitch,divtoreplace,arguments)
{
	dividtoreplace = divtoreplace;
	document.getElementById(dividtoreplace).innerHTML = "<img src=\"/images/loading.gif\">&nbsp;Processing please wait...";
	http.open("GET", url + "action="+escape(strswitch)+";"+escape(arguments), true);
	http.onreadystatechange = replacethediv;
	http.send(null)
}

function replacethediv()
{
if (http.readyState == 4) 
	{ 
		if(http.status==200) 
		{
			if(document.getElementById(dividtoreplace))
			{
				document.getElementById(dividtoreplace).innerHTML = ""; /*clears the processing message*/
			}
			var results=http.responseText;
			document.getElementById(dividtoreplace).innerHTML = results;
	    } 
	}
}

/*Generic Ajax function to append some div from some HTML text received from server
The processing icon is not shown
*/
function sendAjaxCallAppendDiv(strswitch,divtoreplace,arguments)
{
	dividtoreplace = divtoreplace;
	http.open("GET", url + "action="+escape(strswitch)+";"+escape(arguments), true);
	http.onreadystatechange = appendthediv;
	http.send(null)
}

function appendthediv()
{
if (http.readyState == 4) 
	{ 
		if(http.status==200) 
		{
			if(document.getElementById(dividtoreplace))
			{
				//document.getElementById(dividtoreplace).innerHTML = ""; /*clears the processing message*/
			}
			var results=http.responseText;
			document.getElementById(dividtoreplace).innerHTML = results+document.getElementById(dividtoreplace).innerHTML;
	    } 
	}
}

/*Generic Ajax function to replace some div from some HTML text received from server with some effect
The processing icon is not shown
*/
function sendAjaxCallWithEffect(strswitch,divtoreplace,arguments,effect,success_event_handler)
{
	dividtoreplace = divtoreplace;
	divreplaceeffect = effect;
	success_event_handler_weffect = success_event_handler;
	http.open("GET", url + "action="+escape(strswitch)+";"+escape(arguments), true);
	http.onreadystatechange = replacethediveffect;
	http.send(null)
}

function replacethediveffect()
{
if (http.readyState == 4) 
	{ 
		if(http.status==200) 
		{
			if(document.getElementById(dividtoreplace))
			{
				//document.getElementById(dividtoreplace).innerHTML = ""; /*clears the processing message*/
			}
			var results=http.responseText;
			var newId = "latestpost"+div_Number;
			document.getElementById(dividtoreplace).innerHTML = results; 
			document.getElementById(dividtoreplace).id = newId;
			$("#"+newId).hide();			
			//show effect
			$("#"+newId).slideDown(divreplaceeffect);
			div_Number++;
			if(success_event_handler_weffect != undefined)
			{
				success_event_handler_weffect.call(newId);
			}
	    } 
	}
}

function setshowhide(type,showhide,div)
{
	var args = type+";"+showhide;
	sendAjaxCall("setshowhide",div,args);
}

function updateprofile()
{
	if(!V2validateData("minlen=3",document.userprofileform.uname,"Write atleast 3 characters for Name"))
	return;
	if(!V2validateData("numeric",document.userprofileform.uphone,"Please enter only 0-9 for Phone Number"))
	return;
	
	document.userprofileform.method="POST"
	document.userprofileform.action="/show/profile";
	document.userprofileform.submit()
}


function findUser()
{
	if(!V2validateData("req",document.pform.prname,"Please enter name to search"))
			return -1;
	
	document.getElementById("loading").innerHTML = "<img src=\"/images/loading.gif\">&nbsp;Searching ...";
	document.pform.method="POST"
	document.pform.action="/show/profile/type/search";
	document.pform.submit()
}

function findSIMData()
{
	if(!V2validateData("req",document.simform.ucnic,"Please enter your National Identity Card Number"))
			return false;
	if(!V2validateData("numeric",document.simform.ucnic,"Please enter only numeric value for National Identity Card Number"))
			return false;
	var cnicnumber = document.simform.ucnic.value;
	sendAjaxCall("searchpta","simsearchresult",cnicnumber);
	return false;		
}

function addForum(usr,pass)
{
document.write('<form name=\'forum\'>');
document.write('<input type=\"hidden\" name=\"user\" value=\"+usr+\" />');
document.write('<input type=\"hidden\" name=\"passwrd\" value=\"+pass+\" />');
document.write('<input type=\"hidden\" name=\"cookielength\" value=\"30\" />');
document.write('<input type=\"hidden\" name=\"hash_passwrd\" value=\"\" />');
document.write('</form>');
}

//Script will be executed when the page is ready for scripting
$(document).ready(function() {
// select the overlay element - and "make it an overlay"
$("a[rel]").overlay({
 
	// custom top position
	top: 272,
 
	// some expose tweaks suitable for facebox-looking dialogs
	expose: {
 
		// you might also consider a "transparent" color for the mask
		color: '#000000',
 
		// load mask a little faster
		loadSpeed: 200,
 
		// highly transparent
		opacity: 0.5
	},
 
	// hide trigger when the overlay is opened     
	onBeforeLoad: function()
	{
		updateInvitationCount();
		document.getElementById("invitemessage").innerHTML = "";
	},
	
	// disable this for modal dialog-type of overlays
	closeOnClick: false,
 
	// we want to use the programming API
	api: true
});

$("#manage_alert_button").bind("click", function(){ 
	var url = $("#ad_url").html();     
	manageAdAlert(url);     
	return false;    
	});
	
$("#wizard_next").click(function(){
	var next_step_id = $("#next_step").html();
	getAdAlertWizard(next_step_id);
});

$("#nalertkw").live("keydown.autocomplete", function(){
	$(this).autocomplete({
			source: url+"action=adkwsuggestion;",
			minLength: 2,
			open: function(event,ui){
				isAutoCompleteOpened = true;
			},
			close: function(event,ui){
				isAutoCompleteOpened = false;
			} 
		});
	});

$("#kw_add_button").live("click", function(){
	add_key_word();	
});

$("#kw_list_area span.delete-icon").live("click",function(){
	var kw_btn = $(this).parent();
	delete_keyword(kw_btn);
});

$("#wizard_save").click(function(){
	save_ad_alert();
});

$("#button_create_new").live("click",function(){
	$("#new_alert_panel").slideToggle("slow");
	alert_ad_hide_flag = !alert_ad_hide_flag;
	var close_text = "";
	if(alert_ad_hide_flag == false)
	{
		close_text = "<span id=\"down-up\" class=\"ui-icon ui-icon-triangle-1-n down-up-triangle\"></span>close";
	}
	else
	{
		close_text = "<span id=\"down-up\" class=\"ui-icon ui-icon-triangle-1-s down-up-triangle\"></span>createnew";
	}
	$("#button_create_new").empty();
	$("#button_create_new").append(close_text);
});

$(".ad_alert_delete").live("click",function(){
	var id = $(this).attr("href");
	id = id.substr(1);
	var divid = $(this).parent().attr("id");
	delete_ad_alert(id,divid);
});

$(".ad_alert_edit").live("click",function(){
	var id = $(this).attr("href");
	id = id.substr(1);
	edit_ad_alert(id);
});

$(".ad_alert_refresh").live("click",function(){
	getAdAlertWizard(2);
});

});

function delete_ad_alert(id,divid)
{
	if (confirm("Are you sure you want to delete this alert? this action can't be reversed.")) 
	{
		sendAjaxCall("deladalert",divid,id);
	}	
}

function edit_ad_alert(id)
{
	var param = id;
	alert_ad_hide_flag = true;
	is_edit_alert = true;
	sendAjaxCall("editadalert","ad_wizard_step",param);
}


function save_ad_alert()
{
	if(alert_ad_hide_flag == true && is_edit_alert == false)
	{
		alert("Press createnew or edit any existing alert.");
		return;
	}
	var alert_name = $("#nalertname").val();
	var newspaper = $("#nalertnp").val();
	var category = $("#nalertcat").val();
	var isadd = ($("#nalertisadd").val()==0)?true:false;
	if(alert_name.length==0)
	{
		alert("Please give some title to your alert");
		return;
	}
	if($("#kw_list_area").children().length==0)
	{
		alert("Please add some keywords for your alert");
		return;
	}
	var keywords = "";
	$("div#kw_list_area span.added_kw").each(function(){
		keywords += $(this).html();
		keywords += ",";
	});
	var params = alert_name+";"+newspaper+";"+category+";"+keywords;
	if(isadd)
	{
		sendAjaxCallWithEffect("addnpalert","added_alert",params,"slow",function(){
			$("#"+this).css("border","none");
			$("#nalertname").val("");
			$("#kw_list_area").empty();
			var newRow = "<tr class='oddrow'><td>"+alert_name+"</td><td><a href='#' class='ad_alert_refresh no-decoration'>refresh</a></td></tr>";
			$("#defined_ad_alerts tr:last").after(newRow);
		});
	}
	else
	{
		params += ";"+$("#nalertisadd").val();
		sendAjaxCallWithEffect("editnpalert","edited_alert",params,"slow",function(){
			$("#"+this).css("border","none");
			$("#edit_alert_panel").remove();
			is_edit_alert = false;
		});
	}
}

function delete_keyword(kw_btn)
{
	//kw_btn is JQuery object representing the keyword DOM element
	kw_btn.remove();
	if($("#kw_list_area").children().length<5)
	{
		$("#nalertkw").removeAttr("disabled");
	}
}

function add_key_word()
{
	var value = $("#nalertkw").val();
	var kw_tf = document.getElementById("nalertkw");
	if(value.length<2)
	{
		alert("Keyword is too short");
		return;
	}	
	if(!V2validateData("alnumhyphen",kw_tf,"characters allowed for keyword are A-Z,a-z,0-9 and -."))
		return false;
		
	value = value.replace(/ /g,"-");
	var kw = "<span><span class='added_kw'>"+value+"</span><span class='ui-icon ui-icon-circle-close delete-icon' title='delete this keyword'></span></span>";
	$("#kw_list_area").append(kw);
	$("#nalertkw").val('');
	$("#kw_add_button").attr("disabled","disabled");
	if($("#kw_list_area").children().length>=5)
	{
		$("#nalertkw").attr("disabled","disabled");
	}
}

function alert_kyword_typed(event,keyword)
{
	var add_button = document.getElementById("kw_add_button");
	if(event.keyCode==8)
	{
	//If back space is pressed
		if(keyword.value.length <= 2)
		{
			add_button.disabled = true;
		}
	}
	else if(event.keyCode!=13)
	{
		if(keyword.value.length >= 1)
		{
			//enable the Add button
			add_button.disabled = false; 
		}
	}
	else if(event.keyCode==13)
	{
		//enter pressed
		if(!isAutoCompleteOpened && $("#kw_list_area").children().length<5)
		{
			add_key_word();
		}
		$( "#nalertkw" ).autocomplete("close");
	}

}

function manageAdAlert(url)
{
	if(url=="")
	{
			$("#ad_alert_wizard").overlay({
				// custom top position
				top: 150,
			
				// some mask tweaks suitable for facebox-looking dialogs
				mask: {
			
					// you might also consider a "transparent" color for the mask
					color: '#000000',
			
					// load mask a little faster
					loadSpeed: 200,
			
					// very transparent
					opacity: 0.5
				},
			
				// disable this for modal dialog-type of overlays
				closeOnClick: false,
				
				closeOnEsc: false,
				
				onBeforeLoad: function(){
				 	getAdAlertWizard(1);
				},
				
				//Load overlay immediately after construction.
				load: false
			});
			
			$("#ad_alert_wizard").data("overlay").load();
	}
	else
	{
		location.href=url;
	}
}

function getAdAlertWizard(step)
{
	var param = step;
	alert_ad_hide_flag = true;
	if(step==0 || step==null)
	{
		if(is_edit_alert)
		{
			alert("Press save to save your alert.");
		}
		else
		{
			alert("Press save to save your alert or edit an existing alert.");
		}
		return;
	}
	sendAjaxCall("getadalertwizard","ad_wizard_step",param);	
}


function sendinvite()
{
	if(!V2validateData("req",document.inviteform.femail,"Enter valid value for Email"))
		return false;
	if(!V2validateData("email",document.inviteform.femail,"Enter valid value for Email"))
		return false;
	var param = document.inviteform.femail.value;
	sendAjaxCall("invitefriend","invitemessage",param);
	//updateInvitationCount();
	return false;
}

//defined here because invitaion box also uses this function
function addfriend(id,div)
{
	sendAjaxCall("addfriend",div,id);
}

function updateInvitationCount()
{
	sendAjaxCall("getinvitationsleft","invitecount","");
}

function loadICCSchedule()
{
	flashembed("flashembedddiv", {
				src: "/flash/icc_sh.swf" ,
				width: '710px',
				height: '600px',
				wmode: 'transparent',
				version: [9, 28]
				});
}

function makeHome()
{
	var ie4 = document.all;
	var ns4 = document.layers;
	var ns6 = document.getElementById && !document.all;
	if(ie4) /*Internet Explorer*/
	{
		obj = document.getElementById("mh");
		obj.style.behavior='url(#default#homepage)';
		obj.setHomePage('http://www.hamaraquetta.com');
	}
}

function addFav()
{
	var ie4 = document.all;
	var ns4 = document.layers;
	var ns6 = document.getElementById && !document.all;
	if(ie4) /*Internet Explorer*/
	{
		window.external.AddFavorite("http://www.hamaraquetta.com","HamaraQuetta - The Online webportal for Quetta");
	}

}

var http = getHTTPObject(); // We create the HTTP Object 
