/**
 * file to handle the JS driven features of SAMA home page
 *
 * @author Karthikeyan
 * @since Jun 20, 2007
 */

function SubmitData(DataType)
{
	var httpRequest;
	
	objStatusMsgDispDiv	= document.getElementById('posting_info_status_disp_'+DataType);
	objProgressDispDiv	= document.getElementById('blog_post_progress_'+DataType);

	if(DataType=='BLOG')
	{
		objBlgDetFrm	= document.frmBlogDetails;
		if(!checkFormValidation(objBlgDetFrm))
			return false;

		objProgressDispDiv.style.display	= '';
		objStatusMsgDispDiv.innerHTML		= '';

		ServerURL		= "SavePostDetails.php?mailid="+encodeURIComponent(objBlgDetFrm.txtEMailID.value);
		ServerURL		+= "&blogurl="+encodeURIComponent(objBlgDetFrm.txtBlogURL.value);
		ServerURL		+= "&type="+DataType;
	}
	else if(DataType=='NEWSLETTER')
	{
		objNewsLttrDetFrm	= document.frmNewsLetter;
		stURLQry	= '';
		if(!checkFormValidation(objNewsLttrDetFrm))
			return false;

		//get all the elements from the form and make the query string
		for (var counter=0; counter < objNewsLttrDetFrm.elements.length; counter += 2)
		{
			if(trim(objNewsLttrDetFrm.elements[counter].value) != '' && trim(objNewsLttrDetFrm.elements[counter+1].value) != '')
			{
				if(stURLQry != '')
					stURLQry += "&";
				stURLQry	= stURLQry + objNewsLttrDetFrm.elements[counter].name +"="+ encodeURIComponent(objNewsLttrDetFrm.elements[counter].value);
				stURLQry	+= "&" + objNewsLttrDetFrm.elements[counter+1].name +"="+ encodeURIComponent(objNewsLttrDetFrm.elements[counter+1].value);
			}
		}
		
		if(stURLQry != '')
		{
			objProgressDispDiv.style.display	= '';
			objStatusMsgDispDiv.innerHTML		= '';

			ServerURL = "SavePostDetails.php?" + stURLQry + "&type="+DataType;
		}
		else
			return false;
	}
	else
	{
		return false;
	}

	httpRequest = CreateHTTPConnection();

	if (httpRequest)
	{
		httpRequest.onreadystatechange = function() { ShowPostStatus(httpRequest, DataType); };
		httpRequest.open('GET', ServerURL, true);
		httpRequest.send(null);
	}
}

function ShowPostStatus(httpRequest, DataType)
{
	objStatusMsgDispDiv	= document.getElementById('posting_info_status_disp_'+DataType);
	objProgressDispDiv	= document.getElementById('blog_post_progress_'+DataType);

	try
	{
		if (httpRequest.readyState == 4)
		{
			if (httpRequest.status == 200)
			{
				objStatusMsgDispDiv.innerHTML		= httpRequest.responseText;
				objStatusMsgDispDiv.style.display	= '';
				objProgressDispDiv.style.display	= 'none';
				
				//clear the form values
				if(DataType == 'BLOG')
				{
					objBlgDetFrm					= document.frmBlogDetails;
					objBlgDetFrm.txtEMailID.value	= '';
					objBlgDetFrm.txtBlogURL.value	= '';
				}
				else if(DataType == 'NEWSLETTER')
				{
					//get all the elements from the form and make it empty
					for (var counter=0; counter < objNewsLttrDetFrm.elements.length; counter ++)
					{
						objNewsLttrDetFrm.elements[counter].value = '';
					}
				}
			}
			else
			{
				alert('There was a problem with the request.');
			}
		}
	}
	catch( e )
	{
		alert('Caught Exception: ' + e.description);
	}
}

function AddAnotherName(argImgURL)
{
	objNameTable	= document.getElementById('NamesTable');

	objNewRow		= document.createElement("tr");

	//create TD for providing space on both side of the input element
	objSpaceTD				= document.createElement("td");
	objSpaceTD.width		='9';
	objSpaceTD.align		='left';
	objSpaceTD.valign		='top';
	stSpaceImg				= "<img src='"+argImgURL+"/spacer.gif' width='9' height='1' />";
	objSpaceTD.innerHTML	= stSpaceImg;
	//append the left space TD
	objNewRow.appendChild(objSpaceTD);
	//alert(objNewRow);

	//Intialize TD
	objTD			= document.createElement("td");
	objTD.setAttribute("height","26");
	objTD.align		= "left";
	objTD.setAttribute("valign","top");

	//create the name input element
	objInpt				= document.createElement("Input");
	objInpt.name		= "txtRecomdedName[]";
	objInpt.className	= "txt3";
	objInpt.setAttribute("valid", "n_o");
	objInpt.setAttribute("errname", "Name");

	//append the element into TD and then TD into TR
	objTD.appendChild(objInpt);
	objNewRow.appendChild(objTD);


	//Reinitialize TD
	objTD				= document.createElement("td");
	objTD.setAttribute("height","26");
	objTD.align			= "left";
	objTD.setAttribute("valign","top");
	//Reinitialize Input
	objInpt				= document.createElement("Input");
	objInpt.name		= "txtRecomdedMail[]";
	objInpt.className	= "txt3";
	objInpt.setAttribute("valid", "n_e");
	objInpt.setAttribute("errname", "EMail");

	//append the element into TD and then TD into TR
	objTD.appendChild(objInpt);
	objNewRow.appendChild(objTD);

	//append the right space TD
	//objNewRow.appendChild(objSpaceTD);

	objNameTable.appendChild(objNewRow);
}

//function to show a block
//param : id - this id's element will be shown to user
function ShowNewsTab(tobeshownid, ImgName)
{
	//clear of the all status message displayed in the tabs while inserting blog/newsletter details
	objStatusMsgDispDiv					= document.getElementById('posting_info_status_disp_BLOG');
	objStatusMsgDispDiv.innerHTML		= '';
	objStatusMsgDispDiv					= document.getElementById('posting_info_status_disp_NEWSLETTER');
	objStatusMsgDispDiv.innerHTML		= '';

	if (document.getElementById){
		obj		= document.getElementById(tobeshownid);
		TDObj	= document.getElementById(tobeshownid+'TD');
		AObj	= document.getElementById(tobeshownid+'Anchor');
		if (obj){
			obj.style.display		= "";
			TDObj.attributes.getNamedItem('background').nodeValue	= ImgName;
			AObj.className			= 'tahomabold11white';
		}
	}
}

//function to hide a block of element
//param : id - other related element other than this id's element
//will be hidden from user
function HideNewsTabs(nottobehideid, ImgName){
	var divs = document.getElementsByTagName('div');

	for(i=0;i<divs.length;i++){
		var elementid = divs[i].id.replace(/\d/,'');
		var passedid = nottobehideid.replace(/\d/,'');
		if ( divs[i].id != nottobehideid && passedid == elementid ){
			if (document.getElementById){
				obj = document.getElementById(divs[i].id);
				TDObj	= document.getElementById(divs[i].id+'TD');
				AObj	= document.getElementById(divs[i].id+'Anchor');
				if ( obj ){
					obj.style.display = "none";
					TDObj.attributes.getNamedItem('background').nodeValue	= ImgName;
					AObj.className			= 'tahomanormal11b';
				}
			}
		}
	}
}

function ShowRecommendToFriend(stHomeURL, evt)
{
	
	httpRequest	= CreateHTTPConnection();

        if (g_xBalloonManager.hasBalloon("samaBalloon")) {
                balloon.hide();
        }
	X = Y = 0;

	balloon = createBalloon(evt);
	if(httpRequest) {
		if(typeof(pub_url) != 'undefined')
			var URL = pub_url+"/SavePostDetails.php?type=RECOMM_TO_FRIEND&task=DISPLAY";
		else
			var URL = "SavePostDetails.php?type=RECOMM_TO_FRIEND&task=DISPLAY";

		httpRequest.open('GET',URL,true);
		httpRequest.send(null);
		httpRequest.onreadystatechange = function() {
			if (httpRequest.readyState == 4) {
				balloon.contentHtml = httpRequest.responseText;
				balloon.show();
			}
		}
	}
}


function SubmitRecmd2Frnd(evt, stSiteURL)
{
	validEmail				= new RegExp ("^[a-z]+[a-z0-9]*[\.|\-|_]?[a-z0-9]+@([a-z]+[a-z0-9]*[\.|\-]?[a-z]+[a-z0-9]*[a-z0-9]+){1,4}\.[a-z]{2,4}$", "g");
	
	stReferrerEMailID	= document.getElementById('Recmd2Frnd_txtReferrer').value;
	stEmailID	= document.getElementById('Recmd2Frnd_txtEMailIDs').value;
	if(!stReferrerEMailID)
	{
		alert("Please enter your Email ID.");
		document.getElementById('Recmd2Frnd_txtReferrer').focus();
		return false;
	}
	else if(!validEmail.test(stReferrerEMailID))
	{
		alert("The value you entered as your Email ID is incorrect. Please enter a valid Email ID");
		document.getElementById('Recmd2Frnd_txtReferrer').focus();
		return false;
	}

	if(stEmailID)
	{
		stEmailIDRes	= stEmailID.split(",");
		for(counter = 0; counter < stEmailIDRes.length; counter++)
		{
			validEmail				= new RegExp ("^[a-z]+[a-z0-9]*[\.|\-|_]?[a-z0-9]+@([a-z]+[a-z0-9]*[\.|\-]?[a-z]+[a-z0-9]*[a-z0-9]+){1,4}\.[a-z]{2,4}$", "g");
			stEmailIDRes[counter]	= TrimString(stEmailIDRes[counter]);
			if (!validEmail.test(stEmailIDRes[counter]))
			{
				alert("The Email ID("+stEmailIDRes[counter]+") you have entered as (one of) your friend is incorrect. Please enter a valid Email ID");
				document.getElementById('Recmd2Frnd_txtEMailIDs').focus();
				return false;
			}
		}

		httpRequest	= CreateHTTPConnection();

		if (g_xBalloonManager.hasBalloon("samaBalloon"))
		{
			balloon.hide();
		}

		balloon = createBalloon(evt);
		balloon.autoHide=	true;
		balloon.autoHideInterval=	5000;

		//var balloonContentHolder = document.getElementById("divContentHolder");
		if(httpRequest) {
			var stPostURL	= "SavePostDetails.php?type=RECOMM_TO_FRIEND&task=SEND_MAIL&ReferrerEMail="+encodeURIComponent(stReferrerEMailID)+"&ids="+encodeURIComponent(stEmailID);
			httpRequest.open('GET',stPostURL,true);
			httpRequest.send(null);
			httpRequest.onreadystatechange = function() {
				if (httpRequest.readyState == 4) {
					balloon.contentHtml = httpRequest.responseText;
					balloon.show();
				}
			}
		}
	}
	else
	{
		alert('Please enter your friends Email IDs.');
	}
}


function Recmd2Frnd_SubmitOnEnter(e, stSiteURL)
{
	if ( (e && e.keyCode == 13) || (e.charCode == 13)){
		SubmitRecmd2Frnd(e, stSiteURL);
	}
}

function CreateHTTPConnection()
{
	if (window.XMLHttpRequest)
	{ // Mozilla, Safari, ...
		httpRequest = new XMLHttpRequest();
		if (httpRequest.overrideMimeType)
		{
			httpRequest.overrideMimeType('text/xml');
			// See note below about this line
		}
	}
	else if (window.ActiveXObject)
	{ // IE
		try
		{
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e)
			{}
		}
	}

	if (!httpRequest)
	{
		alert('Cannot create a connection to server to send details. Please try later.');
		return false;
	}

	return httpRequest;
}

function TrimString(sString)
{
	while (sString.substring(0,1) == ' ')
	{
		sString = sString.substring(1, sString.length);
	}

	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}


function ToggleFeedbackPromo(show)
{
	objFBPromo	= document.getElementById('FeedbackPromo');
	if(show)
	{
		initFade();
		objFBPromo.style.display	= 'block';
	}
	else
	{
		objFBPromo.style.display	= 'none';
		setCookie('FeedbackPromo',true,now);
	}
}

function TakeToFeedback(URL)
{
	setCookie('FeedbackPromo',true,now);
	if(location.href)
	{
		location.href = URL;
	}
	else
	{
		document.location = URL;
	}
}

function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}

function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

function initFade() {
	for (var i=0;i<9;i++)
		setTimeout('setOpacity('+i+')',100*i);
	return false;
}

function setOpacity(value)
{
	objFBPromo	= document.getElementById('FeedbackPromo');
	objFBPromo.style.opacity = value/10;
	objFBPromo.style.filter = 'alpha(opacity=' + value*10 + ')';
}


function ToggleFont(toggle)
{
	objTogleTxt	= document.getElementById('fonttoggletext');

	var theRules = false;

	for(iterator = 0; iterator < document.styleSheets.length; iterator++)
	{
		if(document.styleSheets[iterator].cssRules)
		{
			objTemp1Rule	= document.styleSheets[iterator].cssRules;
			len			= objTemp1Rule.length;
		}
		else if(document.styleSheets[iterator].rules)
		{
			objTemp1Rule	= document.styleSheets[iterator].rules;
			len			= objTemp1Rule.length;
		}

		if(len == "2")
		{
			if (document.styleSheets[iterator].cssRules)
			{
				objTempRules	= document.styleSheets[iterator].cssRules;
				for(int_iterator = 0; int_iterator < objTempRules.length; int_iterator++)
				{
					if(objTempRules[int_iterator].selectorText == '.verdanaregular11b')
					{
						theRules = document.styleSheets[iterator].cssRules;
					}
				}
			}
			else if (document.styleSheets[iterator].rules)
			{
				objTempRules	= document.styleSheets[iterator].rules;
				for(int_iterator = 0; int_iterator < objTempRules.length; int_iterator++)
				{
					if(objTempRules[int_iterator].selectorText == '.verdanaregular11b')
					{
						theRules = document.styleSheets[iterator].rules;
						break;
					}
				}
			}
		}
	}

	if(theRules)
	{
		//for the news item toggle
		for(iterator = 0; iterator < theRules.length; iterator++)
		{
			if(theRules[iterator].selectorText == '.verdanaregular11b')
			{
				if(toggle == 'increase')
					theRules[iterator].style.fontSize = '12px';
				else
					theRules[iterator].style.fontSize = '11px';
			}
		}

		//for the news title toggle
		for(iterator = 0; iterator < theRules.length; iterator++)
		{
			if(theRules[iterator].selectorText == '.tahomabold12blue')
			{
				if(toggle == 'increase')
					theRules[iterator].style.fontSize = '13px';
				else
					theRules[iterator].style.fontSize = '12px';
			}
		}
	}

	/*if(toggle == 'increase')
	{
		document.getElementById('increasefont').style.display = 'none';
		document.getElementById('decreasefont').style.display = 'block';
	}
	else
	{
		document.getElementById('increasefont').style.display = 'block';
		document.getElementById('decreasefont').style.display = 'none';
	} */
}


function submitNL()
{
	var httpRequest;
	objStatusMsgDispNLDiv	= document.getElementById('postingNEWSLETTER');
	objProgressDispNLDiv	= document.getElementById('postprogressNEWSLETTER');
		
	objNLfrm = document.newsletter;
	var user_name = document.getElementById("nluserEmailid");
        var max_username_length = 60;
        var username_length = user_name.length;
        var valUname = user_name.value;

        if(!valUname) {
                alert("Please enter your Email ID");
                user_name.focus();
                return false;
        }
        if(valUname.indexOf('')>0) {
                alert("Email ID cannot contain spaces");
                user_name.focus();
                return false;
        }
                if (username_length > max_username_length) {
                alert("Email ID can contain a  maximum of " + max_username_length + " characters only\n");
                return false;
        }
        validEmail = new RegExp ("^[a-z]+[a-z0-9]*[\.|\-|_]?[a-z0-9]+@([a-z]+[a-z0-9]*[\.|\-]?[a-z]+[a-z0-9]*[a-z0-9]+){1,4}\.[a-z]{2,4}$", "g");
        if (!validEmail.test(valUname)) {
                        alert("Please enter a valid Email ID");
                        return false;
        }
	
	stNLURLQry = '';
	
	
//	if(!checkFormValidation(objNLfrm))
//		return false;
	stNLURLQry = objNLfrm.nluserEmailid.value;
	if(stNLURLQry != '')
	{
		objProgressDispNLDiv.style.display	= '';
		objStatusMsgDispNLDiv.innerHTML		= '';
		ServerURL = "newsletterDetails.php?email="+stNLURLQry;
	}
	else
	{
		return false;
	}
	
	
	httpRequest = CreateHTTPConnection();

	if (httpRequest)
	{
		httpRequest.onreadystatechange = function() { newsletterPostStatus(httpRequest); };
		httpRequest.open('GET', ServerURL, true);
		httpRequest.send(null);
	}	
}



function newsletterPostStatus(httpRequest)
{

	objStatusMsgDispNLDiv	= document.getElementById('postingNEWSLETTER');
	objProgressDispNLDiv	= document.getElementById('postprogressNEWSLETTER');

	try
	{
		if (httpRequest.readyState == 4)
		{
			if (httpRequest.status == 200)
			{
				objStatusMsgDispNLDiv.innerHTML		= httpRequest.responseText;
				objStatusMsgDispNLDiv.style.display	= '';
				objProgressDispNLDiv.style.display	= 'none';
				objNLfrm.nluserEmailid.value = 'Enter your mail ID';
			}
			else
			{
				alert('There was a problem with the request.');
			}
		}
	}
	catch( e )
	{
		alert('Caught Exception: ' + e.description);
	}
}
