function createObject()
{
	var request_type;
	var browser = navigator.appName;
	if(browser == "Microsoft Internet Explorer"){
		request_type = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else
	{
		request_type = new XMLHttpRequest();
	}
	return request_type;
}

var http = createObject();



var nocache = 0;
var ok = '<img src="../images/true.gif">';
var notOk = '<img src="../images/false.gif">';



function addcoment()
{
	if(validated()){
		var noComment = document.getElementById('noComment').innerHTML;
		// Optional: Show a waiting message in the layer with ID ajax_response
		var savingImage = '<table align="center" border="0" width="21%" id="table1"><tr><td align="center" width="50"><img border="0" src="../images/savingComent.gif" ></td><td align="center" width="105">Saving Your Comment...</td></tr></table>';
		document.getElementById('saving').innerHTML = savingImage;
		//document.getElementById('saving').innerHTML = "<img src='../images/loadingNew.gif' alt='Saving Please Wait...'>"
		// Required: verify that all fileds is not empty. Use encodeURI() to solve some issues about character encoding.
		
		var name= encodeURI(document.getElementById('name').value);
		var email= encodeURI(document.getElementById('email').value);
		var website= encodeURI(document.getElementById('website').value);
		var commenttext= encodeURI(document.getElementById('commenttext').value);
		var aid= encodeURI(document.getElementById('aid').value);
		var vcode = encodeURI(document.getElementById('vcode').value);
		
		// Set te random number to add to URL request
		nocache = Math.random();
		
		// Pass the login variables like URL variable
		http.open('get', 'addcoment.php?name='+name+'&email='+email+'&aid= '+aid+'&commenttext= '+commenttext+'&website= '+website+'&vcode= '+vcode);
		//alert ("Every thing is fine");
		http.onreadystatechange = loginReply;
		http.send(null);
		clearAll();
	}//ending validation
		
}


function makeArray() {
	for (i = 0; i<makeArray.arguments.length; i++)
	{
		this[i + 1] = makeArray.arguments[i];
	}
}

function loginReply()
{
		//var failed = false;
		if(http.readyState == 4)
		{
			var response = http.responseText;
			//alert(response);
			
			if(response == 1)
			{
				// if login fails
				//failed = true;
				//document.getElementById('noComment').innerHTML = noComment + '<font color="red">Failed to add comments because you reached the limit of 5 comments for today.</font>';
				// else if comment is ok show a message: "mean comment is added".
				document.getElementById('saving').innerHTML = "";
				document.getElementById('saving').innerHTML = '<font color="red"><b><center>Invalid Verification Code Entered.</center></b></font>';
				document.getElementById("vimgmessage").innerHTML=notOk;
				reloadVImg("vimg");
			}
			else if(response == 2)
			{
				// if login fails
				//failed = true;
				//document.getElementById('noComment').innerHTML = noComment + '<font color="red">Failed to add comments because you reached the limit of 5 comments for today.</font>';
				// else if comment is ok show a message: "mean comment is added".
				document.getElementById('saving').innerHTML = "";
				document.getElementById('saving').innerHTML = '<font color="red"><b><center>You have already posted one comment.</center></b></font>';
				document.getElementById("vimgmessage").innerHTML=notOk;
				reloadVImg("vimg");
			}
			else if(response == 0)
			{
				// if login fails
				document.getElementById('saving').innerHTML = "";
				document.getElementById('saving').innerHTML = '<font color="red"><b><center>Failed to add comments because you reached the limit of 2 comments for today.</center></b></font>';
				//document.getElementById('noComment').innerHTML = noComment + '<font color="red">Failed to add comments because you reached the limit of 3 comments for today.</font>';
				// else if comment is ok show a message: "mean comment is added".
			}
			else
			{
				/*
				function makeArray() {
				for (i = 0; i<makeArray.arguments.length; i++)
				this[i + 1] = makeArray.arguments[i];
				}
				
				var months = new makeArray('January','February','March','April','May',
				'June','July','August','September','October','November','December');
				var date = new Date();
				var day = date.getDate();
				var month = date.getMonth() + 1;
				var yy = date.getYear();
				var year = (yy < 1000) ? yy + 1900 : yy;
				
				document.write(day + " " + months[month] + " " + year);
				*/		
				
				var months = new makeArray('Jan','Feb','Mar','Apr','May',
				'Jun','Jul','Aug','Sep','Oct','Nov','Dec');
				var date = new Date();
				var day = date.getDate();
				var month = date.getMonth() + 1;
				var yy = date.getYear();
				var year = (yy < 1000) ? yy + 1900 : yy;
				
				
				var noComment = document.getElementById('noComment').innerHTML;
				//document.getElementById('noComment').innerHTML="";
			
				var name= encodeURI(document.getElementById('name').value);
				var email= encodeURI(document.getElementById('email').value);
				var website= encodeURI(document.getElementById('website').value);
				var commenttext= encodeURI(document.getElementById('commenttext').value);
				var aid= encodeURI(document.getElementById('aid').value);
				
				commenttext = replaceSubstring(commenttext,"%20"," ");
				commenttext = replaceSubstring(commenttext,"%E2%80%99","’");
				commenttext = replaceSubstring(commenttext,"%0A","<br>");
			
				var newComment = '<div class="CommentArea"><h4 class="CommentTitle">';
			
				if(website!="" && website!='http://'){
					newComment += '<b><a class="commentanchor" style="text-transform: uppercase;" rel="nofollow" target="_blank" href="' + website + '" title="' + replaceSubstring(name,"%20"," ") + '\'s New Comment added">' + replaceSubstring(name,"%20"," ") + '</a> <font color="000000">Said:</font></b>';
				}else{
					newComment += '<b><font style="text-transform: uppercase;" color="#006ff7">' + replaceSubstring(name,"%20"," ") + '</font> <font color="000000">Said:</font></b>';
				}
			
				newComment += '<img class="CommentArrow" src="../images/spacer.gif" title="' + replaceSubstring(name,"%20"," ") + '\'s New Comment Added" alt="' + replaceSubstring(name,"%20"," ") + '\'s New Comment Added" style="border-width: 0px;" align="bottom"></h4>';
				newComment += '<div class="CommentText"><div class="CommentText2">Your comment is awaiting moderation.<div class="CommentText3">';
				
				//newComment += "<div class='post-date' style='width: 45px; height: 49px'><span class='post-month'>Feb</span> <span class='post-day'>03</span>  <span class='post-year'>09</span></div>";
				newComment += "<div class='post-date' style='width: 45px; height: 49px'><span class='post-month'>" + months[month] + "</span> <span class='post-day'>" + day + "</span>  <span class='post-year'>" + year +"</span></div>";
				newComment += commenttext;
				newComment += "</div><!--CommentText3 end--></div><!--CommentText2 end--></div><!--CommentTex end-->";
				newComment += "</div><!--CommentArea end-->";
			
				reloadVImg("vimg");
				document.getElementById('noComment').innerHTML = noComment + newComment;
				document.getElementById('saving').innerHTML = "";
			}//end else
		}//end if
	

}//end function

function clearAll(){
	//Reseting the all fields of coment adding form
	//document.addcomentform.name.value = "Enter Your Name";
	//document.addcomentform.email.value = "E-mail Address";
	//document.addcomentform.website.value = "http://";
	//document.addcomentform.commenttext.value = "";
	document.getElementById("namemessage").innerHTML = "";
	document.getElementById("emailmessage").innerHTML = "";
	document.getElementById("websitemessage").innerHTML = "";
	document.getElementById("commenttextmessage").innerHTML = "";
	document.getElementById("vimgmessage").innerHTML = "";
}

function validated(){
	var empty_string = /^\s*$/;
	var result = true;
	if(empty_string.test(document.addcomentform.email.value) || document.addcomentform.email.value == "E-mail Address"){
		document.getElementById("emailmessage").innerHTML = notOk;
		result = false;
	}else if (!isValidEmail(document.addcomentform.email.value)) 
	{ 
		document.getElementById("emailmessage").innerHTML = notOk;
		result = false;
	}else
	{
		document.getElementById("emailmessage").innerHTML = ok;
	}
	
	if(empty_string.test(document.addcomentform.name.value) || document.addcomentform.name.value == "Enter Your Name"){
		document.getElementById("namemessage").innerHTML = notOk;
		result = false;
	}else{
		document.getElementById("namemessage").innerHTML = ok;
	}
	
	
	if(empty_string.test(document.addcomentform.commenttext.value)){
		document.getElementById("commenttextmessage").innerHTML = notOk;
		result = false;
	}else{
		document.getElementById("commenttextmessage").innerHTML = ok;
	}
	
	if(empty_string.test(document.addcomentform.vcode.value)){
		document.getElementById("vimgmessage").innerHTML = notOk;
		result = false;
	}else{
		document.getElementById("vimgmessage").innerHTML = ok;
	}

	
	if(result){
		result = checkURL();
	}
	

	return result;
}

function ceckValidity(formName,inputName){
	var txt = "";
	//alert(inputName);
	if (isValidEmail(document.forms['addcomentform'].email.value)) 
	{ 
		txt = ok;

	} else { 
		txt = notOk; 
	}
	document.getElementById("emailmessage").innerHTML=txt;
}

function isValidEmail(emailAddress) {
     var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
     return re.test(emailAddress);
}

function nameChanged(){
	if(document.addcomentform.name.value!="" && document.addcomentform.name.value!="Enter Your Name"){
		document.getElementById("namemessage").innerHTML=ok;
	}else{
		document.getElementById("namemessage").innerHTML=notOk;
	}
}

function vimgChanged(){
	if(document.addcomentform.vcode.value!="" && document.addcomentform.vcode.value.length==5){
		document.getElementById("vimgmessage").innerHTML=ok;
	}else{
		document.getElementById("vimgmessage").innerHTML=notOk;
	}
}

function reloadVImg(id) {
   var obj = document.getElementById(id);
   var src = obj.src;
   var pos = src.indexOf('?');
   if (pos >= 0) {
      src = src.substr(0, pos);
   }
   var date = new Date();
   obj.src = src + '?v=' + date.getTime();
   return false;
}

function commentChanged(){
	if(document.addcomentform.commenttext.value!=""){
		document.getElementById("commenttextmessage").innerHTML=ok;
	}else{
		document.getElementById("commenttextmessage").innerHTML=notOk;
	}
}


function checkURL(){
	if(document.addcomentform.website.value=="http://"){
		//alert("URL is defaule");
		return true;
	}else if (document.addcomentform.website.value==""){
		//alert("URL is defaule");
		return true;
	}else{
		var urlIs = document.addcomentform.website.value;
		//alert("Changed url");
		
		if (isValidURL(urlIs))
		{
			document.getElementById("websitemessage").innerHTML=ok;
			//alert ("Valid URL");
			return true;
		}
		else{
			document.getElementById("websitemessage").innerHTML=notOk;
			//alert ("Not a Valid URL");			
			return false;
		}
		
		/*
		if (urlIs.indexOf("http://") != "0")
		{
			document.getElementById("websitemessage").innerHTML=ok;
		}
		else{
			document.getElementById("websitemessage").innerHTML=notOk;
		}
		*/
	}
}

function isValidURL(url) {
	var regExis = /^((http)|(HTTP)):\/\//
	if (!regExis.test(url)) {
		//alert ("oops - not a valid URL");
		return false;
	}else{
		//alert ("URL is OK");
		return true;
	} 
}


function isEmpty(elementValue){
	var empty_string = /^\s*$/;
	return empty_string.test(elementValue)
}

function clearField(field) {
  // Check if field contains the default value
  if (field.value == field.defaultValue) {
    // It does, so clear the field
    field.value = "";
  }
}

function checkField(field) {
  // Check if user has entered information in the field
  if (field.value == "") {
    // User has not entered anything
    field.value = field.defaultValue;
  }
}

function formtool_count_chars(textField, countField, maxlen,show_alert) {
	if(textField != null && textField.value != null) {
		if (textField.value.length > maxlen){
	    	if(show_alert){
	        	alert('This field cannot exceed ' +  maxlen + ' characters.');
	        }
			textField.value = textField.value.substring(0, maxlen);
		} else {
			countField.value = maxlen - textField.value.length;
		}
	}
}
	
function checkAgainURL(field) {
  // Check if user has entered information in the field
  if (field.value == "" || field.value == "http://") {
    // User has not entered anything
    field.value = field.defaultValue;
    document.getElementById("websitemessage").innerHTML="";
  }
}


function replaceSubstring(inputString, fromString, toString) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function
