var obj_timer = null;
var interval = 6000;
var morezeoles ="";
//var xmlHttp = null;

function test(){
 alert("testfun");
}


function fbs_click(id) {
    var url="http://www.zeole.com/s.php/?zid="+id;
    //     u=location.href;
    //t=document.title;
    window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(url),'sharer','toolbar=0,status=0,width=626,height=436');
    //window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(url)+'&t='+encodeURIComponent(title),'sharer','toolbar=0,status=0,width=626,height=436');
    return false;
}

function getAjax(){
    //    var xmlHttp;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    try
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    catch (e)
      {
      alert("Your browser does not support AJAX!");
      return false;
      }
    } //End Catch

  }//EndCatch
  return   xmlHttp;
}

//xmlHttp = getAjax();
 function zeoleMouseClick() {

    var user = document.form.uname.value;
    //    alert(user );
    if( user == "" ){
	window.location = "http://zeole.com/HTML/login.html";
	return;
    }
    var container=document.getElementById("zingcontainer");
    container.style.height=420;
    
    container.innerHTML="  <div style=\"position:relative;\">	\
                           <div class=\"zingboxtext\"><p><b>Title (Optional)</b></p> </div>  \
                           <textarea class=\"zingboxtitle\" name=\"title\" id=\"title\"></textarea> \
                           <div class=\"zingboxtext\"><p><b>Zeole (1400 Characters) </b></p></div>\
                           <textarea class=\"zingbox\" id=\"zing\" onKeyUp=\"limitText(this.form.zing,this.form.countdown,5000);\" onKeyUp=\"limitText(this.form.zing,this.form.countdown,25000);\" ></textarea> \
	      </div>\
	      <div  style=\"position:relative;height:100px;width500px;\">\
	           <br>\
                   <input type=\"button\" class=\"button_example\" style=\"position:absolute;left:150px;\" id=\"shout\" value=\"Zeole It!\" onclick=\"sendzing();\" />\
        <input type=\"button\" class=\"button_example\" id=\"shoutcancel\"  value=\"Cancel\" style=\"position:absolute;left:250px;\" onclick=\"minimizeZing();\" /> </div>";

    var obj=document.getElementById("zing");
    obj.style.height=250;

    if ( obj.value == "Start typing your Zeole here..." ){
	obj.value = "";
    }
    obj.select();
    document.form.title.focus();
}

function minimizeZing(){
    var container=document.getElementById("zingcontainer");
    container.style.height=40;

    container.innerHTML="<div style=\"position:relative; \">   \
 	        <textarea class=\"zingboxtitle\" id=\"zing\" onClick=\"zeoleMouseClick();\">Start typing your Zeole here...</textarea> \
	      </div>";

    var obj=document.getElementById("zing");
    obj.style.height=30;
}

function minimizeComment(id) {
    //alert("minimizeComment");
    var container=document.getElementById("commentcontainer"+id);
    container.style.height=25;
    container.innerHTML='<input type="submit" value="Add Comment" class="button_comment" onClick="maximizeComment('+id+');return false;"/>';
        if ( obj_timer == null){
	obj_timer= self.setInterval("ajaxFunction()",interval);
	//alert(obj_timer);
    }

}

function maximizeComment(id) {
    var user_obj = document.getElementById('uname');
    var user = user_obj.value;
    if( user == "" ){
	window.location = "http://zeole.com/HTML/login.html";
        return;
    }


    if (obj_timer){
	clearInterval(obj_timer);
	obj_timer = null;
    } 
    //alert(obj_timer);
    //alert(id);


    
    var container=document.getElementById("commentcontainer"+id);
    container.style.height=300;

    container.innerHTML="<br><br>Posts your comments <br> <textarea type='text'  class='comment' id='commentTextarea"+id+"'></textarea>\
        <br><br>								\
        <input type='submit' value='Comment' 'class='button_comment_expand' onClick='sendComment("+id+");'/> \
        <input type='submit' value='Cancel' class='button_comment_expand' onClick='minimizeComment("+id+");'/><br>";
    var obj=document.getElementById("commentTextarea"+id);
    obj.style.height=200;
}

function sendComment(id){
	var zing_id = id;
	var result = "";
	//alert(id);
	result = document.getElementById("commentTextarea"+id).value;
	minimizeComment(id);
	
	result=commentreplace(result);

	if (obj_timer == null){
	    obj_timer= self.setInterval("ajaxFunction()",interval); 
	    //alert(obj_timer);
	}

	var params = "zeole_id="+zing_id+"&comment=" +encodeURIComponent(result);

	var xmlHttp = getAjax();
	xmlHttp.onreadystatechange=function() {
	    if(xmlHttp.readyState==4) {
		var ob=document.getElementById("commentcontainer"+id);
		ob.style.height=25;
		ob.innerHTML='<input type="submit" value="Add Comment" class="button_comment" onClick="maximizeComment('+id+');return false;"/>';
	    }
	}

	var url = "/PHP/serveraddcomment.php?"+new Date().getTime();
	xmlHttp.open("POST",url,true);
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlHttp.send(params);
	// WARNING: any code after send will hang firefox!
	//document.getElementById("commentTextarea").value = "";
	//settimeout("minimizeComment()",1000);
	self.setTimeout("ajaxFunction()",500);
	var maxc="showComment("+id +")";
	self.setTimeout(maxc,1500);
}


function sendzeoleComment(id){
	var zing_id = id;
	var result = "";
	//alert(id);
	result = document.getElementById("commenttextbox").value;

	result=commentreplace(result);
	var params = "zeole_id="+zing_id+"&comment=" +encodeURIComponent(result);

	var xmlHttp = getAjax();
	xmlHttp.onreadystatechange=function() {
	    if(xmlHttp.readyState==4) {
		var ob=document.getElementById("commentcontainer"+id);
		ob.style.height=25;
		ob.innerHTML='<input type="submit" value="Add Comment" class="button_comment" onClick="maximizeComment('+id+');return false;"/>';
	    }
	}

	var url = "/PHP/serveraddcomment.php?"+new Date().getTime();
	xmlHttp.open("POST",url,true);
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	xmlHttp.send(params);
	document.getElementById("commenttextbox").value = "";
	setTimeout("location.reload(true);",2000);
}



function replace( zingText ){
    var replaced_string = "";
    replaced_string = zingText.replace(/</g,"&lt;");
    replaced_string = replaced_string.replace(/>/g,"&gt;");
    //replaced_string = replaced_string.replace(/'/g,"&#39;");
    replaced_string = replaced_string.replace(/[\s\t\r\n\v\f]+$/,"");
    //    replaced_string = replaced_string.replace(/\n/g,"<br>");
    return replaced_string;
}


function commentreplace( zingText ){
    var replaced_string = "";
    replaced_string = zingText.replace(/</g,"&lt;");
    replaced_string = replaced_string.replace(/>/g,"&gt;");
    replaced_string = replaced_string.replace(/[\s\t\r\n\v\f]+$/,"");
    //replaced_string = replaced_string.replace(/'/g,"&#39;");
    replaced_string = replacelink(replaced_string);
    replaced_string = replaced_string.replace(/\n/g,"<br>");
    return replaced_string;
}

function replacelink( zing ){
    var index;
    var result="";
    var rest="";
    var spaceChar;
    var link;

index = linkStart ( zing );


	while ( index != -1 ) {
	        //store eveything before the link
		result += zing.substring(0,index) ;

		//Extract rest of the sentence
		rest = zing.substring( index );

		//Now to Extract the link from this link ends with a blank line 
		spaceChar = linkEnd ( rest );

		if( spaceChar != -1) {
			link = rest.substring(0,spaceChar);
		}
		else{
			link = rest;
			spaceChar = -1;
		}

		//Create anchor tag
		if( rest.substring(0,3)  == "www" ){
			link = "<a target=\"_blank\" href='http://" + link + "'>" + link + "</a>";
		}
		else{
			link = "<a target=\"_blank\" href='" + link + "'>" + link + "</a>";
		}
		result += link ;

		//one link sucessfully processed
		//Start with the next link if its present.
		if( spaceChar == -1 ){
		    zing = "";
		    break;
		}
		
		//New Search String
		zing = rest.substring(spaceChar);
		index = linkStart( zing );
	}

	result += zing;

	return result;
}

function updateZingDiv ( title, zing ){
    zing = zing.replace(/\n/g,"<br>");
    var zingbox = document.getElementById("zings");
    var user = document.form.uname.value;
    
    var newzing =  "<div class='zmessagenew'>\
                          <div class='messagetitle'>" + title + "</div> \
		          <div class='message'><br> " + zing + " <br><br></div> \
		          <div class='nameAndTime'>\
			      <div class='name'> " + user + "</div>\
			      <div class='time'>0 minuites ago</div>\
		          </div>\
                          <div class='zingseparator'></div>\
	            </div>";

    //    var newzing = "<div class='zmessagenew'><div class='nameAndTime'><span class='name'> " + user +"</span><span class='time'> 0 minuites ago</span></div><div class='message'> <p>" + zing + "</p> </div></div> ";

    zingbox.innerHTML = newzing + zingbox.innerHTML;
}


function linkStart( data ) {
    var startindex = -1;
    var indexhttp = -1;
    var indexwww = -1;
    indexhttp = data.search("http");
    indexwww = data.search("www");
    if (indexhttp < indexwww ){
	startindex = (indexhttp != -1 )? indexhttp: indexwww;
    }
    else {
	startindex = (indexwww != -1 )? indexwww: indexhttp;
    }

    return startindex;
}

function linkEnd( data ) {
    var endindex = -1;
    var indexspace = -1;
    var indexenter = -1;
    indexspace = data.search(" ");
    indexenter = data.search("\n");
    if (indexenter < indexspace ){
	endindex = (indexenter != -1 )? indexenter: indexspace;
    }
    else {
	endindex = (indexspace != -1 )? indexspace: indexenter;
    }

    return endindex;
}

function sendzing(){
	var index=0;
	var spaceChar = 0;
	var link = "";
	var oldindex = 0;
	var zing = "";
	var result = "";
	var afterLink = "";

	zing = replace(document.form.zing.value);
	
	//zing = document.form.zing.value;
	index = linkStart ( zing );

	//alert("end of fx()");

	while ( index != -1 ) {
	        //store eveything before the link
		result += zing.substring(0,index) ;

		//Extract rest of the sentence
		rest = zing.substring( index );

		//Now to Extract the link from this link ends with a blank line 
		spaceChar = linkEnd ( rest );

		if( spaceChar != -1) {
			link = rest.substring(0,spaceChar);
		}
		else{
			link = rest;
			spaceChar = -1;
		}

		//Create anchor tag
		if( rest.substring(0,3)  == "www" ){
			link = "<a target=\"_blank\" href='http://" + link + "'>" + link + "</a>";
		}
		else{
			link = "<a target=\"_blank\" href='" + link + "'>" + link + "</a>";
		}
		result += link ;

		//one link sucessfully processed
		//Start with the next link if its present.
		if( spaceChar == -1 ){
		    zing = "";
		    break;
		}
		
		//New Search String
		zing = rest.substring(spaceChar);
		index = linkStart( zing );
	}

	result += zing;


	result = result.replace(/\n/g,"<br>");

	
	//result = document.form.zing.value;
	//alert("Point A");
	var titlestr=replace(document.form.title.value);
    var params = "zing=" + encodeURIComponent(result) + "&title=" +encodeURIComponent(titlestr);
    //alert("Point B");
    var xmlHttp = getAjax();
    //alert("Point C");
    var url = "/PHP/serveraddzing.php?"+new Date().getTime();
    xmlHttp.open("POST",url,true);
    //alert("Point D");
    xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	//    xmlHttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	//    xmlHttp.setRequestHeader("Pragma", "no-cache");
	//    xmlHttp.setRequestHeader("Expires", "-1");
    //xmlHttp.setRequestHeader("Content-Length", params.length);
    // xmlHttp.setRequestHeader("Connection", "close");
    //alert("Point E");
    //alert(params);
    xmlHttp.send(params);
    //alert("Point F");



    //send mail
    


    document.getElementById("zing").value = "";
    self.setTimeout("ajaxFunction()",1000);
    minimizeZing();
}

function delete_zing(id){
    var user = document.form.uname.value;
    var userConfirm = false;
    var confirmstring = user + " are you sure you want to delete this zeole?";

    userConfirm = confirm(confirmstring,"Delete Warning");

    if( userConfirm == false ){
	return false;
    }

    var params = "zeole_id=" + id;
    var xmlHttp = getAjax();
    var url = "/PHP/serverdeletezing.php?"+new Date().getTime();
    xmlHttp.open("POST",url,true);

    xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlHttp.send(params);

    self.setTimeout("ajaxFunction()",500);
    ajaxFunction();

    return true;
}


function ajaxFunction()
{
    //  document.statusbar(); //displays statusbar 
    //alert("abc");
    var  xmlHttp = getAjax();
  xmlHttp.onreadystatechange=function()
    {
    if(xmlHttp.readyState==4 && xmlHttp.status == 200)
      {
	  //	  alert(xmlHttp.responseCode);
	  //	  alert(morezeoles);
      var ob=document.getElementById("zings");
      //bug here. new post will push the 15th zeole out.
      ob.innerHTML =  xmlHttp.responseText + morezeoles;
      }
    }
  xmlHttp.open("POST","/PHP/serverside.php",true);
  xmlHttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
  xmlHttp.setRequestHeader("Pragma", "no-cache");
  xmlHttp.setRequestHeader("Expires", "-1");
  xmlHttp.send(null);
}

function logout(){
    window.location="/PHP/logout.php";
}


function draw(){
         var value= "<tr valign='top'>                                                     \
         <td bgcolor='rgb(120, 160, 160)' width='80'>                                       \
             <table width='80' cellspacing='0' cellpadding='0' height='80'>                  \
             <tr bgcolor='#FFFFFF'>                                                           \
             <td><img src='/IMAGES/PROFILES/$image' width='80' height='80'></td>         \
             </tr>                                                                              \
             </table>                                                                           \
         </td>                                                                                  \
         <td bgcolor='#C3D9FF' width='800'>                                                     \
             <table width='100%' border='0' cellspacing='0' cellpadding='3' height='80%'>       \
             <tr valign='top'>                                                                  \
                 <td align='right'>                                                             \
                 <font face='Verdana, Arial, Helvetica, sans-serif' size='1'>                   \
                   Posted by $username on $time                                                 \
                 </font>                                                                        \
                 </td> \
             </tr>            \
             <tr valign='center'> \
                 <td>      \
                     $message   \
                 </td>     \
             </tr>    \
             </table>    \
         </td>           \
     </tr>";
     var ob=document.getElementById("zings");
     ob.innerHTML   = value;

}

function get_client_location(){
    document.getElementbyId('Country').innerHTML="Initial";
    if(google.loader.ClientLocation)
	{
	    visitor_lat = google.loader.ClientLocation.latitude;
	    visitor_lon = google.loader.ClientLocation.longitude;
	    visitor_city = google.loader.ClientLocation.address.city;
	    visitor_region = google.loader.ClientLocation.address.region;
	    visitor_country = google.loader.ClientLocation.address.country;
	    visitor_countrycode = google.loader.ClientLocation.address.country_code;
	    document.getElementbyId("Country").innerHTML="if";
	}
    else
	{
	    // ClientLocation not found or not populated
	    // so perform error handling
	    document.getElementbyId('Country').innerHTML="Error";
	}
}

function showcommentBox(id){

    // var divbox=document.getElementbyId('comdiv-940');
    //divbox.innerHTML="<textarea rows='4' cols='40'></textarea>";
        alert(id);

}



function registerpopup(){
   
   var container=document.getElementById("popupcontainer");
   var popupbox=document.getElementById("popup");

   var registerpop='<div id="login">\
      <div class="auth_box">\
	<form name="login" action="/PHP/register.php" method="post">	\
	  <h2>New user registration</h2>\
	  Email_id &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="email_id" class="login"/>\
          <br>	  <br>\
	  Preferred name&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <input type="text" name="username" class="login"/>\
	  <br>   <br>\
	  Password  &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <input type="password" name="password1" class="login"/>\
	  <br>   <br>\
	  Retype Password &nbsp&nbsp <input type="password" name="password2" class="login"/>\
	  <br>   <br>\
	  Your home city &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<input type="text" name="location" class="login"/>\
	  <br>   <br>\
	  <input type="submit" value="Register" class="button_2"/>\
	  <br>\
	  <br>\
	</form>\
      </div>\
 <a href="#" style="position:absolute;left:30px;top:5px" onclick="loginpopup()">Login</a>\
 |\
 <a href="#" style="position:absolute;left:100px;top:5px" onclick="registerpopup()">Register</a>\
 <a href="#" style="position:absolute;right:15px;top:5px" onclick="hide()">close</a>';



   popupbox.style.visibility="visible";
   container.innerHTML=registerpop;
   //   alert("inside");

 }


   function loginpopup(){
   var container=document.getElementById("popupcontainer");
   var popupbox=document.getElementById("popup");
var loginpop='<div id="login">	\
      <div class="auth_box">\
      <div class="loginheading">Login</div><br>\
        <form name="login" action="/PHP/authenticate.php" method="post">\
	  <div class="login_text">Email ID  &nbsp; </div>\
	  <input type="text" name="email" class="login"/>\
	  <br>\
	  <div class="login_text">Password </div>\
	  <input type="password" name="password" class="login"/>\
	  <br>\
	  <span align=center> \
	  <input type="submit" value="Login" class="button_example"/>\
	  </span>\
          <br>\
	  <br>\
	  <a href="#" onclick="registerpopup()"> Click here to Register as new user</a>\
       </form>\
    </div>\
 </div> \
 <a href="#" style="position:absolute;left:30px;top:5px" onclick="loginpopup()">Login</a>\
 |\
 <a href="#" style="position:absolute;left:100px;top:5px" onclick="registerpopup()">Register</a>\
 <a href="#" style="position:absolute;right:15px;top:5px" onclick="hide()">close</a>';

   popupbox.style.visibility="visible";
   container.innerHTML=loginpop;
   //   alert("inside");
 }


   function hide(){


   var popupbox=document.getElementById("popup");
   popupbox.style.visibility="hidden";

   }


function zeoleprev(){

    var zeoles=document.getElementsByName("zeolediv");
    var firstzeoleId = zeoles[0].id;
    getprevzeoles(firstzeoleId);
}

function zeolenext(){

    var zeoles=document.getElementsByName("zeolediv");
    var lastzeoleId = zeoles[zeoles.length - 1 ].id;
    lastzeoleId = lastzeoleId.substr(4);
    getnextzeoles(lastzeoleId);
}


function checkfrontPage(){

    var zeoles=document.getElementsByName("zeolediv");
    var lastzeoleId = zeoles[zeoles.length - 1 ].id;
    if( lastzeoleId >= maxzeoleId){

	alert("frontPage");
    }

}


function getprevzeoles( zeoleId )
{

    var  xmlHttp = getAjax();
  xmlHttp.onreadystatechange=function()
    {
    if(xmlHttp.readyState==4)
      {
      var ob=document.getElementById("zings");
      var response = trim(xmlHttp.responseText);
      if(response != "" ){
	  ob.innerHTML =  xmlHttp.responseText + ob.innerHTML;
      }
      }
    }
  var params="operation=prev&id="+zeoleId;
  xmlHttp.open("POST","/PHP/getnextprevzeoles.php",true);
  xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xmlHttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
  xmlHttp.setRequestHeader("Pragma", "no-cache");
  xmlHttp.setRequestHeader("Expires", "-1");
  xmlHttp.send(params);
  //  self.setTimeout("checkfrontPage()",500);
  //self.setTimeout("checkfrontPage()",500);

}


function getnextzeoles(zeoleId)
{

    var  xmlHttp = getAjax();
  xmlHttp.onreadystatechange=function()
    {
    if(xmlHttp.readyState==4)
      {
      var ob=document.getElementById("zings");
      morezeoles = morezeoles + xmlHttp.responseText;
      ajaxFunction();
      }
    }

  var params="operation=next&id="+zeoleId;
  xmlHttp.open("POST","/PHP/getnextprevzeoles.php",true);
  xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xmlHttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
  xmlHttp.setRequestHeader("Pragma", "no-cache");
  xmlHttp.setRequestHeader("Expires", "-1");
  xmlHttp.send(params);

}

function hideComment(id){

    var numcomment=document.getElementById("numcom_"+id);
    var count=numcomment.value;
    var commentview=document.getElementById("viewcom_"+id);
    commentview.innerHTML = "<input  type='button' value='View "+count+" Comments' class='button_more_comment' onClick='showComment(" + id + ");' />";
    var comment_container=document.getElementById("co-"+id);
    comment_container.innerHTML = "";

}

function showComment(id){

    if (obj_timer){
        clearInterval(obj_timer);
        obj_timer = null;
    }

    var commentview=document.getElementById("viewcom_"+id);
    commentview.innerHTML = "<input  type='button' value='Hide Comments' class='button_more_comment' onClick='hideComment("+id  +");' />";
    var container=document.getElementById("commentcontainer"+id);
    var  xmlHttp = getAjax();
    xmlHttp.onreadystatechange=function()
	{
    
	    if(xmlHttp.readyState==4)
		{
		    var comment_container=document.getElementById("co-"+id);
		    comment_container.innerHTML = xmlHttp.responseText;

		}
	}

    var params="cid="+id;
    xmlHttp.open("POST","/PHP/getcomments.php",true);
    xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    xmlHttp.setRequestHeader("Pragma", "no-cache");
    xmlHttp.setRequestHeader("Expires", "-1");
    xmlHttp.send(params);

}


function getuserzeole(uid)
{
    //  document.statusbar(); //displays statusbar 
    //alert("abc");
    var  xmlHttp = getAjax();
  xmlHttp.onreadystatechange=function()
    {
    if(xmlHttp.readyState==4)
      {
	  //	  alert(morezeoles);
      var ob=document.getElementById("zings");
      //bug here. new post will push the 15th zeole out.
      ob.innerHTML =  xmlHttp.responseText + morezeoles;
      }
    }
  url="/PHP/getuserzeoles.php/?uid="+uid;
  xmlHttp.open("GET",url,true);
  xmlHttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
  xmlHttp.setRequestHeader("Pragma", "no-cache");
  xmlHttp.setRequestHeader("Expires", "-1");
  xmlHttp.send(null);
}
