//main js functions for the site
var elem = false;
var encKey = "jaslkj34lkjals98098asdjlkjlkasd7987987";
var xmlResp = "failed";
var eppHtmlToPdfUrl = "http://e-powered.net/services/htmltopdf/att3/htmltopdf.php";

function submitEmailSignup() {
	var uemail = document.getElementById("dmcEmailInput").value;
	if(uemail != "" && uemail != "Email") {
	    window.location.href = "http://annieslist.com/Content.aspx?p=Signup&EmailSend=" + uemail;	
	} else {
		alert("Please enter your email");	
	}
}

function submitEmailSignupModal() {
	var uemail = document.getElementById("dmcEmailInput").value;
	if(uemail != "" && uemail != "your@email.com") {
		
		fireModal("#messModal_signup");
		
		$.get("../dmc_main/server.aspx", "pi=mspext&ui=ui&process=signup_modal&email=" + uemail,
		function (data) {
			$("#messModal_signup_cont").html("You'll receive your first Lunch Deal tomorrow!");
		});
		
	} else {
		alert("Please enter your email");	
	}
}

function submitSearch() {
	var sterm = document.getElementById("dmcSearchInput").value;
	var mode = document.getElementById("dmcSearchMode").value;
	if(mode != "none") {
		switch(mode) {
			case "aui_sct":
				window.location.href = "plugin.aspx?pi=core&mode=aui&process=search_content_files&searchText="+sterm;
			break;
			case "aui_sd":
				window.location.href = "plugin.aspx?pi=core&mode=auid&process=search_content_files&searchText="+sterm;
			break;
			case "aui_sa":
				window.location.href = "plugin.aspx?pi=core&mode=auia&process=search_content_files&searchText="+sterm;
			break;
			case "aui_posts":
				window.location.href = "plugin.aspx?pi=core&mode=auiposts&process=search_content_files&searchText="+sterm;
			break;
			case "aui_cct":
				window.location.href = "plugin.aspx?pi=core&mode=auicore&process=search_content_files&searchText="+sterm;
			break;
			case "aui_cd":
				window.location.href = "plugin.aspx?pi=core&mode=auicored&process=search_content_files&searchText="+sterm;
			break;
			case "aui_ca":
				window.location.href = "plugin.aspx?pi=core&mode=auicorea&process=search_content_files&searchText="+sterm;
			break;
			default:
				window.location.href = "Search.aspx?process=search_content_files&searchText="+sterm;
			break;
		}	
	} else {
		alert("Please select a search mode");	
	}
}

function changeTms(tmsFile) {
	var currentPage = window.location.href;
	var urlHash = getUrlVars();
	if(urlHash["tmsid"] != undefined && urlHash["tmsid"] != "") {
		if(currentPage.indexOf("?") > 0) {
			currentPage = currentPage.replace("&tmsid="+urlHash["tmsid"]+"","");
			currentPage = currentPage.replace("tmsid="+urlHash["tmsid"]+"","");
			currentPage += "&tmsid=tms/"+tmsFile+".txt";	
		} else {
			currentPage = currentPage.replace("tmsid="+urlHash["tmsid"]+"","");
			currentPage += "tmsid=tms/"+tmsFile+".txt";
		}
		window.location.href = currentPage;	
	} else {
		if(currentPage.indexOf("?") > 0) {
			currentPage = currentPage.replace("&tmsid="+urlHash["tmsid"]+"","");
			currentPage = currentPage.replace("tmsid="+urlHash["tmsid"]+"","");
			currentPage += "&tmsid=tms/"+tmsFile+".txt";	
		} else {
			currentPage += "?tmsid=tms/"+tmsFile+".txt";
		}
		window.location.href = currentPage;
	}
}

function siteSubmitLoginAux() {
	var pw = document.form1.pw.value;	
	var un = document.form1.uname.value;
	var rememberMe = false;
	if(pw != "" && un != "") {
		
		$("#loginResp").html("processing login...");
		
		if(document.form1.rememberMe.checked == true) {
			rememberMe = true;
			createCookie("DMCSiteLoginName",un,"10");
			createCookie("DMCSiteLoginPw",pw,"10");
		}
		window.location.href = "Login.aspx?process=do_login&uname="+un+"&pw="+pw;	
	} else {
		alert("Please include your username and password");
	}
}

function checkCookieSiteLogin() {
	var cln = readCookie("DMCSiteLoginName");
	var clp = readCookie("DMCSiteLoginPw");
	if(cln !== null) {
		document.form1.uname.value = cln;
	}
	if(clp !== null) {
		document.form1.pw.value = clp;
	}
}

function checkCookieDMCLogin() {
	var cln = readCookie("DMCCoreLoginName");
	var clp = readCookie("DMCCoreLoginPw");
	if(cln !== null) {
		document.form1.uname.value = cln;
	}
	if(clp !== null) {
		document.form1.pw.value = clp;
	}
}

function dmcParentSubmit(urlLink) {
	parent.location = urlLink;
}

function writeFormFrame() {
	var urlHash = getUrlVars();
	if(urlHash["EmailSend"] != "" && urlHash["EmailSend"] !== undefined && urlHash["ZipSend"] != "" && urlHash["ZipSend"] !== undefined) {
	    document.getElementById("dmcFrameCont").innerHTML = "<iframe frameborder=\"0\" width=\"100%\" scrolling=\"no\" src=\"http://annieslist.com/Frames/Signup.aspx?EmailSend=" + urlHash["EmailSend"] + "&ZipSend=" + urlHash["ZipSend"] + "\" style=\"border: 0px none ; margin: 0px; padding: 0px; height: 550px; width: 100%;\" marginheight=\"0\" marginwidth=\"0\" allowtransparency=\"true\"></iframe>";
	} else if(urlHash["EmailSend"] != "" && urlHash["EmailSend"] !== undefined) {
	    document.getElementById("dmcFrameCont").innerHTML = "<iframe frameborder=\"0\" width=\"100%\" scrolling=\"no\" src=\"http://annieslist.com/Frames/Signup.aspx?EmailSend=" + urlHash["EmailSend"] + "\" style=\"border: 0px none ; margin: 0px; padding: 0px; height: 550px; width: 100%;\" marginheight=\"0\" marginwidth=\"0\" allowtransparency=\"true\"></iframe>";
	} else if(urlHash["ZipSend"] != "" && urlHash["ZipSend"] !== undefined) {
	    document.getElementById("dmcFrameCont").innerHTML = "<iframe frameborder=\"0\" width=\"100%\" scrolling=\"no\" src=\"http://annieslist.com/Frames/Signup.aspx?ZipSend=" + urlHash["ZipSend"] + "\" style=\"border: 0px none ; margin: 0px; padding: 0px; height: 550px; width: 100%;\" marginheight=\"0\" marginwidth=\"0\" allowtransparency=\"true\"></iframe>";
	} else {
	    document.getElementById("dmcFrameCont").innerHTML = "<iframe frameborder=\"0\" width=\"100%\" scrolling=\"no\" src=\"http://annieslist.com/Frames/Signup.aspx\" style=\"border: 0px none ; margin: 0px; padding: 0px; height: 500px; width: 100%;\" marginheight=\"0\" marginwidth=\"0\" allowtransparency=\"true\"></iframe>";
	}
}

function new_window(url) {
	link = window.open(url,"Link","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width=400,height=450,left=80,top=180");
}

function openPrintText_pop(title, filePath, dmcPath) {
	var url = dmcPath+"print.aspx?process=get_file&path="+filePath+"&title="+title;
	var name = "dmc_print";
	window.open(url,name,"toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=500,height=450,top=80,left=80");
}

function openPrinterFriendly(filePath) {
	var url = filePath;
	var name="Print";
	window.open(url ,name,"toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=700,height=450,top=80,left=80");
}

function clearMessResp() {
	$("#mess_resp").html("&nbsp;");
}

function updateMessResp(msg) {
	$("#mess_resp").html(msg);
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+escape(value)+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function dmcHtmlToPdf(dataUrl, baseUrl) {
/**
this function uses the dmc php pdf convertor provided by PHP Classes
**/
	window.open(eppHtmlToPdfUrl+"?urlPath="+escape(dataUrl)+"&urlBase="+baseUrl);
}

function submitValForm_dyn(formName,subPath,retPath,required) {
/*
Use this function to validate a form and then submit it to a destination

formName string : name of form you are submitting
subPath string : URL to submit form data to (ie: dynFormSub.php)
retPath string : URL to return form response to
required string : comma seperated list of required field names (ie: name,phone,email)
*/
	var data = new Array();
	var required_arr = new Array();
	var myForm;
	var qstring = '';
	var error = 0;
	required_arr = required.split(",");
	switch(formName) {
		case 'dmc_login_form':
			myForm = document.dmc_login_form.elements;
		break;
	}
	for(var i=0; i<myForm.length; i++) {
		data[myForm[i].name] = myForm[i].value;
		qstring += '&'+myForm[i].name+'='+myForm[i].value;
	}
	qstring += '&form_name='+formName;
	qstring += '&rURL='+retPath;
	
	if(required_arr.length > 0) {
		for(i=0;i<required_arr.length;i++) {
			if(data[required_arr[i]] == '') {
				error++;
			}	
		}
		if(error == 0) {
			document.location.href = subPath+'?'+qstring;
		} else {
			alert('Please include all required fields');
		}
	} else {
		document.location.href = subPath+'?'+qstring;
	}
}

//---------------------encryption------------------

/*
js/encrypt.js must be included to function.
*/

function dmcEncrypt(encValue)
{
	var resp;
	resp = textToBase64(rc4(encKey,encValue));
	return resp;
}

function dmcDecrypt(encValue)
{
	var resp;
	resp = rc4(encKey,base64ToText(encValue));
	return resp;
}

/*
Add bookmark script
*/

/* This script and many more are available free online at
The JavaScript Source :: http://javascript.internet.com
Created by: Philip Myers :: http://virtualipod.tripod.com/bookmark.html */

function bookmark(url,title){
  if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)) {
  window.external.AddFavorite(url,title);
  } else if (navigator.appName == "Netscape") {
    window.sidebar.addPanel(title,url,"");
  } else {
    alert("Press CTRL-D (Netscape) or CTRL-T (Opera) to bookmark");
  }
}

/*
Add bookmark script
*/

//---------------------utility---------------------

function getUrlVars()
{
/**
Example for URL http://www.example.com/index.html?hello=bonjour&goodevening=bonsoir

var hash = getUrlVars();
alert(hash['hello']); // prints 'bonjour'
alert(hash['goodevening']); // prints 'bonsoir'
**/
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	for(var i = 0; i < hashes.length; i++)
	{
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
}

function getUrlVarsParent()
{
/**
Example for URL http://www.example.com/index.html?hello=bonjour&goodevening=bonsoir

var hash = getUrlVars();
alert(hash['hello']); // prints 'bonjour'
alert(hash['goodevening']); // prints 'bonsoir'
**/
	var vars = [], hash;
	var hashes = parent.location.href.slice(parent.location.href.indexOf('?') + 1).split('&');
	for(var i = 0; i < hashes.length; i++)
	{
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
}

function getQueryString() {
	var qstring = window.location.search.substring(1);
	return qstring;
} 

function redirectUrlSelect(elemID) {
	var selValue = getSelectValueById(elemID);
	window.location.href = selValue;
}

function getSelectValueById(elemID) {
	var selValue = document.getElementById(elemID).options[document.getElementById(elemID).selectedIndex].value;
	return selValue;
}

function chkObjectExists(inParent,theVal) {
/**
Written by Kumar S
http://www.guyfromchennai.com/?p=20

inParent bool - if true, looks in window.opener
theVal string - element id
**/
	if(inParent){
		if (window.opener.document.getElementById(theVal) != null) {
			return true;
		} else {
			return false;
		}
	} else {
		if (document.getElementById(theVal) != null) {
			return true;
		} else {
			return false;
		}
	}
}

function sanitizeServerAjaxCall(encText){
	var resp = encText;
	resp = resp.replace(/<div id="dmc_aui_cont">/,"");
	resp = resp.replace(/<\/div>/,"");
	return resp;
}

function whenLoading(){
	var e = document.getElementById('mess_resp'); 
	e.innerHTML = "Sending Data...";
}

function whenLoaded(){
	var e = document.getElementById('mess_resp'); 
	e.innerHTML = "Data Sent...";
}

function whenInteractive(){
	var e = document.getElementById('mess_resp'); 
	e.innerHTML = "Processing data...";
}

function openWindow(url,height,width,top,left,resize) {
	var myRand = parseInt(Math.random()*999999999);
	var name = "RandWindow_"+myRand;
	window.open(url,name,"toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable="+resize+",width="+width+",height="+height+",top="+top+",left="+left+"");
}

function pause(numberMillis) 
{
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
		return;
	}
} 

function pausecomp(millis)
{
	var date = new Date();
	var curDate = null;
	
	do { curDate = new Date(); }
	while(curDate-date < millis);
} 

function openBrowseServer_fck(mode,path) {
/*
mode options: File Flash Image Media or none for all
*/
	var url;
	var name = 'ai_pop_browser';
	if(mode == 'none') {
		url = path+'cms/FCKeditor/editor/filemanager/browser/default/browser.html?Connector=connectors/asp/connector.asp';
	} else {
		url = path+'cms/FCKeditor/editor/filemanager/browser/default/browser.html?Type='+mode+'&Connector=connectors/asp/connector.asp';
	}
	window.open(url,name,"toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1,width=700,height=450,top=80,left=80");
}

// --------------------AJAX METHODS VIA SACK ---------------------- //

function sackAjaxRequest(reqFile,method,respElement) {
	var ajax = new sack();
	ajax.requestFile = reqFile;
	ajax.method = method;
	ajax.element = respElement;
	ajax.onLoading = whenLoading;
	ajax.onLoaded = whenLoaded; 
	ajax.onInteractive = whenInteractive;
	//ajax.onCompletion = sackResponse;
	ajax.runAJAX();
}

function sackResponse() {
	return true;
}

// -----------------------jQuery--------------------------------//

function showElement(id) {
	$(id).show("slow");
}

function hideElement(id) {
	$(id).hide("slow");
}

function slideElementUp(id) {
	$(id).slideUp();
}

function slideElementDown(id) {
	$(id).slideDown();
}

function toggleElement(id) {
	$(id).toggle();
}

function fadeElementIn(id) {
	$(id).fadeIn("slow");
}

function fadeElementOut(id) {
	$(id).fadeOut("slow");
}

function slideToggleElem(elemID) {
	$(elemID).slideToggle();	
}

/** jqModal **/
function fireJqModal(dmcTrig, dmcModalElem, dmcTarget) {
	var triggers = $(dmcTrig)[0];
	
	$(dmcModalElem).jqm({
		trigger: triggers,
		/*ajax: 'server.aspx',*/
		target: dmcTarget,
		overlay: 50,
		onHide: function(h) { 
		  h.o.remove(); // remove overlay
		  h.w.fadeOut(888); // hide window 
		},
		onShow: function(h) { 
		  h.w.fadeIn(888); // hide window 
		}
	});
	
	if($.browser.msie) {
		$('div.jqmAlert .jqmClose')
		.hover(
		function(){ $(this).addClass('jqmCloseHover'); }, 
		function(){ $(this).removeClass('jqmCloseHover'); });
	}
}

function fireJqModalAjax(dmcTrig, dmcModalElem, dmcTarget) {
	var triggers = $(dmcTrig)[0];
	
	$(dmcModalElem).jqm({
		trigger: triggers,
		ajax:'@name',
		target: dmcTarget,
		overlay: 50,
		onHide: function(h) { 
		  h.o.remove(); // remove overlay
		  h.w.fadeOut(888); // hide window 
		},
		onShow: function(h) { 
		  h.w.fadeIn(888); // hide window 
		}
	});
	
	if($.browser.msie) {
		$('div.jqmAlert .jqmClose')
		.hover(
		function(){ $(this).addClass('jqmCloseHover'); }, 
		function(){ $(this).removeClass('jqmCloseHover'); });
	}
}

/*jq form method*/
function jqSubmitForm(mode) {
	var data = new Array();
	var myRand = parseInt(Math.random()*999999999);
	var filePath = "dmc_main/server.aspx";
	var myForm = document.form1;
	var today = new Date();
	//var queryString = $("#form1 .jqFormField").fieldSerialize();
	var queryString = "rand="+myRand;
	for(var i=0; i<myForm.length; i++) {
		if(myForm[i].name != "__VIEWSTATE") {
			data[myForm[i].name] = myForm[i].value;
			queryString += '&'+myForm[i].name+'='+escape(myForm[i].value);
		}
	}
	if(queryString.length > 0) {
		//add date added
		queryString += '&da='+today;
		//add date added
		$.get(filePath, queryString ,
		function(data){
			if(sanitizeServerAjaxCall(data) == "success") {
				$("#mess_resp").html("Form successfully submitted. Thank you.");
			} else {
				if(mode == "message") {
					$("#mess_resp").html("Failed to submit form");
				} else if(mode =="data") {
					$("#mess_resp").html(sanitizeServerAjaxCall(data));
				} else {
					$("#mess_resp").html("Failed to submit form");
				}
			}
			setTimeout("clearMessResp()",20000);
		});
	} else {
		$("#mess_resp").html("Please include all required fields");
		setTimeout("clearMessResp()",20000);
	}
}

function jqSubmitContributeForm(mode) {
	var data = new Array();
	var myRand = parseInt(Math.random()*999999999);
	var filePath = "dmc_main/server.aspx";
	var myForm = document.form1;
	var queryString = "rand="+myRand;
	var today = new Date();
	for(var i=0; i<myForm.length; i++) {
		if(myForm[i].name != "__VIEWSTATE") {
			data[myForm[i].name] = myForm[i].value;
			queryString += '&'+myForm[i].name+'='+escape(myForm[i].value);
		}
	}
	if(queryString.length > 0) {
		//add date added
		queryString += '&da='+today;
		//add date added
		$.get(filePath, queryString ,
		function(data){
			$("#mess_resp").html("Transferring to PayPal...");
			$("#PayPalRedirect").html(sanitizeServerAjaxCall(data));
		});
	} else {
		$("#mess_resp").html("Please include all required fields");
		setTimeout("clearMessResp()",20000);
	}
}

function jqSendEmail(toEmail, fromEmail, subjectEmail, bodyEmail) {
	var resp = "failed";
	var filePath = "dmc_main/server.aspx";
	var queryString = "process=send_email&to="+toEmail+"&from="+fromEmail+"&subject="+subjectEmail+"&body="+bodyEmail;
	if(toEmail != "" && fromEmail != "" && subjectEmail != "" && bodyEmail != "") {
		$.get(filePath, queryString ,
		function(data){
			if(sanitizeServerAjaxCall(data) == "success") {
				$("#mess_resp").html("Email successfully delivered. Thank you.");
				resp = "success";
			} else {
				if(mode == "message") {
					$("#mess_resp").html("Failed to send email");
				} else if(mode =="data") {
					$("#mess_resp").html(sanitizeServerAjaxCall(data));
				} else {
					$("#mess_resp").html("Failed to send email");
				}
				resp = "failed";
			}
			setTimeout("clearMessResp()",10000);
		});
	} else {
		$("#mess_resp").html("Failed to send email");
		resp = "failed";
	}
	return resp;
}
