var item;
var INPUT_NAME_PREFIX = 'items';
var tableRows = 0;
var itemArray = new Array();
var newForm = 1;
var theItems="";
var INPUT_NAME_PREFIX = 'inputName'; // this is being set via script
var ROW_BASE = 1; // first number (for display)
var TABLE_NAME = 'lists';
var num = 0;
var firstLoad = 0;
var numRows = 0;
var first = 0;
var tableRows=0;
var prev = " ";
var nextRow = 0;
var xmlHttp=null;
var frstLoad = 0;
var totalItems = 0;
var couponIndex = new Array(30);

/***Function used to output a saved list ****/
function fillInRows() {	
	if(num!=0) {
		clearInnerHTML(document.getElementById('lists'));
		clearInnerHTML(document.getElementById('validCoupons'));
	}
	if(firstLoad == 0) {
		var checkBox = document.getElementById('deleteCheckBox');
		var delBtn = document.getElementById('deleteBtn');
		var reBtn = document.getElementById('resendBtn');
		var selPhone = document.getElementById('selected_number');
		firstLoad = 1;
	}
	box = document.forms[0].selected_list;
	//var items = box.options[box.selectedIndex].value;
	var params = box.options[box.selectedIndex].value;
	var params_array = params.split(",");
	var list_id = params_array[0];
	var items = getUserListByID(list_id); // this function fills the table with the items
	
	var remark = document.getElementById('remark');
	var listName = box.options[box.selectedIndex].innerHTML;
	remark.innerHTML = "Update List: <a href='../list/makelist.php?act=2&id=" +list_id+ "'>"+listName+"</a>";
	printAccessRights(list_id);//output the access rights	
	var accessListID = document.getElementById('access_list_id');
	accessListID.setAttribute('value', list_id);
	//document.access_form.access_list_id.value = list_id;
	getValidCoupons();
}



function formatDate(d) {
	var splited = d.split("-");
	var year = splited[0];
	var month = splited[1];
	var splitagain = splited[2].split(" ");
	var day = splitagain[0];
	var time = month+"/"+day+"/"+year;
	return time;
}

function setStore() {
	var params = box.options[box.selectedIndex].value;
	var params_array = params.split(",");
	var store_id = params_array[1];
	var storeInp = document.getElementById('store');
	storeInp.value = store_id;
}




function addValExistsRowToTable(item) {
	var tbl = document.getElementById('lists');
	
	//Dynamically add the user's input to the items table
	//Create the Row div tag
	var rowDiv = document.createElement('div');
	rowDiv.setAttribute('id', 'rowDiv' + num);
	setClassAttribute(rowDiv, 'items');
	
	var rowDisp = document.createElement('ul');
	setClassAttribute(rowDisp, 'itemline');
	
	//Create the input field that holds the item name
	var listField;
	var showDiscount;
	//we need to check for coupons as well.
	
	listField = document.createElement('li');
	if(item.length > 30) {
		lastspace = itemInput.lastIndexOf(" ");
		low = itemInput.substr(0, lastspace);
		high = itemInput.substr(lastspace, item.length);
		listField.appendChild(document.createTextNode(low));
		listField.appendChild(document.createElement('br'));
		listField.appendChild(document.createTextNode(high));			
		setheight = setRowDivHeight(item);
		rowDiv.style.height = setheight;
	} else {
		listField.appendChild(document.createTextNode(item));
	}
	setClassAttribute(listField, 'itemsaved');
	rowDiv.appendChild(listField);
	if(num%2 == 0) 
		rowDiv.style.background = '#f1f5fa';
	tbl.appendChild(rowDiv);
	num++;
}

function setRowDivHeight(itemstr) {
	strlen = itemstr.length;
	heightCnt = 0;
	pad = 0;
	while(strlen > 0) {
		heightCnt += 20;
		pad += 3.2;
		strlen -= 30;
	} 
	return heightCnt+Math.floor(pad)+'px';
}


function setDeleteList() {
	/*var isName = box.options[box.selectedIndex].id;
	alert("ID: " + box.options[box.selectedIndex].id);
	if(isName!="noName") {
		var setElName = document.getElementById('deleteListDate');
		var listNameDate = box.options[box.selectedIndex].id;	
		setElName.setAttribute('value', listNameDate);
	} else {
		var setItemEl = document.getElementById('deleteListDate');
		var date = box.options[box.selectedIndex].innerHTML;
		setItemEl.setAttribute('value', date);
	}
	*/
}


function email_friend_current_list(){
	box = document.forms[0].selected_list;
	var list_id = box.options[box.selectedIndex].value;
	var listBox = document.getElementById('selected_list');
	window.location= "?id="+list_id+"&action=friend";
}


function print_current_saved_list(){
	var box = document.forms[0].selected_list;
	var list_id = box.options[box.selectedIndex].value;
	var listBox = document.getElementById('selected_list');
	//NewWindow("../list/print_list.php?id="+list_id,"list",'550','550',"yes","center");
	NewWindow("../list/print_list.php?id="+list_id,"list",'550','550',"yes","center");	
}

var win=null;

function NewWindow(mypage,myname,w,h,scroll,pos){
	if(pos=="random"){LeftPosition=(screen.width)?Math.floor(Math.random()*(screen.width-w)):100;TopPosition=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;}
	if(pos=="center"){LeftPosition=(screen.width)?(screen.width-w)/2:100;TopPosition=(screen.height)?(screen.height-h)/2:100;}
	else if((pos!="center" && pos!="random") || pos==null){LeftPosition=0;TopPosition=20}
	settings='width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=yes';
	win=window.open(mypage,myname,settings);
}

function openInNewWindow(frm)
{
	// open a blank window
	var aWindow = window.open('', 'TableAddRow2NewWindow',
	'scrollbars=yes,menubar=yes,resizable=yes,toolbar=no,width=400,height=400');
	
	// set the target to the blank window
	frm.target = 'TableAddRow2NewWindow';
	
	// submit
	frm.submit();
}



function getUserListByID(list_id){
	totalItems = 0;
	if (list_id.length==0)
	{ 
		return "";
	}
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
	{
	alert ("Browser does not support HTTP Request");
	return;
	}
	if (xmlHttp.readyState != 0) {
        xmlHttp.abort();
        alert("xmlHttp was aborted because xmlHttp.readyState != 0");
    }     
	var url="../Scripts/get_list.php";
	url=url+"?id="+list_id;
	url=url+"&sid="+Math.random();
	xmlHttp.open("GET",url,true);
	xmlHttp.onreadystatechange=stateChanged_list; 
	xmlHttp.send(null);
	var listItems = document.getElementById('theListItems');
	return listItems.value;
}



function stateChanged_list(){	
	if (xmlHttp.readyState==4 || xmlHttp.readyState == "completed"){ 
		totalItems++;
		var listItems = document.getElementById('theListItems');	
		listItems.setAttribute('value', xmlHttp.responseText);
		var itemTime = xmlHttp.responseText;
		var splitItem = itemTime.split("->");
		otherstring = splitItem[1].split("!");
		dnctstr = otherstring[1].split("~");	
		id = dnctstr[0].substring(dnctstr[0].indexOf("_-_")+3,dnctstr[0].indexOf("-:"));
		theItems = splitItem[0];
		var dispTime = document.getElementById('postTime');
	
		dispTime.innerHTML = "List created "+otherstring[0];
		
		var brokenstring = theItems.split("#");
		for(i = 0; i < brokenstring.length; i++){
			if(brokenstring[i] != null && brokenstring[i] != "")
				addValExistsRowToTable(brokenstring[i]);
		}
	} 
} 


var xmlHttp_access;

function printAccessRights(list_id){
		if (list_id.length==0)
	{ 
		return "";
	}
	xmlHttp_access=GetXmlHttpObject();
	if (xmlHttp_access==null)
	{
	alert ("Browser does not support HTTP Request");
	return;
	}
	if (xmlHttp_access.readyState != 0) {
        xmlHttp_access.abort();
        alert("xmlHttp_access was aborted because xmlHttp.readyState != 0");
    }     
	var url="../Scripts/get_list_access.php";
	url=url+"?id="+list_id;
	url=url+"&sid="+Math.random();
	xmlHttp_access.open("GET",url,true);
	xmlHttp_access.onreadystatechange=stateChanged_access; 
	xmlHttp_access.send(null);	
}


function stateChanged_access(){
	var accDiv = document.getElementById("access_div");	
	accDiv.innerHTML = "";
	accDiv.style.background = "#FFFFFF";
		
	if (xmlHttp_access.readyState==4 || xmlHttp_access.readyState == "completed"){ 
		accDiv.innerHTML = xmlHttp_access.responseText;	
		//accDiv.style.background = "#EEEEEE";
	} 
	
}

function clearInnerHTML(obj) {
	// so long as obj has children, remove them
	while(obj.firstChild) { 
		obj.removeChild(obj.firstChild);
	}
}

function GetXmlHttpObject()
{ 
var objXMLHttp=null
	
	if (window.XMLHttpRequest)
	{
		objXMLHttp=new XMLHttpRequest()
	}
	else if (window.ActiveXObject)
	{
		objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
	}
	return objXMLHttp;
}

function InitiateXMLHttp() {
	var objXMLHttp=null
	
	if (window.XMLHttpRequest)
	{
		objXMLHttp=new XMLHttpRequest()
	}
	else if (window.ActiveXObject)
	{
		objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
	}
	//alert("objXMLHttp: "+objXMLHttp);
	xmlHttp = objXMLHttp;
} 

function getValidCoupons() {
	
	validCoupons_xmlHttp=GetXmlHttpObject();
	if (validCoupons_xmlHttp==null)
	{
	alert ("Browser does not support HTTP Request");
	return;
	}
	if (validCoupons_xmlHttp.readyState != 0) {
        validCoupons_xmlHttp.abort();
        alert("xmlHttp was aborted because xmlHttp.readyState != 0");
    }     
	var url="../Scripts/get_valid_coupons.php";
	var list_id = box.options[box.selectedIndex].value;
	url=url+"?list_id="+list_id
	
	validCoupons_xmlHttp.open("GET",url,true);
	validCoupons_xmlHttp.onreadystatechange=stateChanged_validCoupons; 
	validCoupons_xmlHttp.send(null);
	
	
}


function stateChanged_validCoupons()
{	
	if (validCoupons_xmlHttp.readyState==4 || validCoupons_xmlHttp.readyState == "completed"){ 
		var theID = "validCoupons";
		var theDiv = document.getElementById(theID);
		if(validCoupons_xmlHttp.responseText != '-1') {
			var validDnctObj = eval("("+validCoupons_xmlHttp.responseText+")");
			for(var i=0; i<validDnctObj.validDiscounts.length; i++) {
				var info = validDnctObj.validDiscounts[i];
				var dDiv = document.createElement('div');
				setClassAttribute(dDiv, 'validCouponsDiv');
				var titlep = document.createElement('p');
				setClassAttribute(titlep, 'validCoupons');
				titlep.appendChild(document.createTextNode(info.title));
				dDiv.appendChild(titlep);
				
				var expiret = document.createElement('p');
				setClassAttribute(expiret, 'validCouponsExpiret');
				expiret.appendChild(document.createTextNode('Valid Until:'));
				dDiv.appendChild(expiret);
				
				var expirep = document.createElement('p');
				setClassAttribute(expirep, 'validCouponsExpire');
				expirep.appendChild(document.createTextNode(info.expire_date));
				dDiv.appendChild(expirep);
				
				var store = document.createElement('p');
				setClassAttribute(store, 'validCouponsStore');
				store.appendChild(document.createTextNode(info.store_name));
				dDiv.appendChild(store);
				
				var add = document.createElement('p');
				setClassAttribute(add, 'validCouponsAdd');
				add.appendChild(document.createTextNode(info.address));
				dDiv.appendChild(add);
				
				var loc = document.createElement('p');
				setClassAttribute(loc, 'validCouponsAdd');
				loc.appendChild(document.createTextNode(info.location));
				dDiv.appendChild(loc);
				
				theDiv.appendChild(dDiv);	
			}
			new Effect.Appear('validCoupons', { duration: 1.0 });
		}
	} 
}


function confirmSendOtherPhoneManageList() {
	regex = /^[- ()0-9]+$/;
	if(theItems == "") {
		return alert("Please add items to your list before sending");
	} else {
		confirmSend = confirm('Do you want to send your list now?');
		if(confirmSend) {
			if(document.form1.txtphone.value != "") {
				//check the length of the number as well
				//since we don't know what sort of characters that will be entered just look between 
				//two estimated values. The characters that are possible are - and ().
				if(document.form1.txtphone.value.length > 9 && document.form1.txtphone.value.length < 15) {
					if(document.form1.txtphone.value.match(regex)) {
							return true;
						} else {
							alert("Please enter a valid phone number, including the area code");
							return false;
						}
				} else {
					alert("Please enter a valid phone number, including the area code");
					return false;
				}
			} else {
				alert("Please enter a valid phone number, including the area code");
				return false;
			}
		}
	}
} 

function confirmSendEmailManageList() {
	regex = /^.+?@.+?\..+$/;
	if(theItems == "") {
		return alert("Please add items to your list before sending");
	} else {
		confirmSend = confirm('Do you want to send your list now?');
		if(confirmSend) {
			if(document.form1.email.value != "") {
				if(document.form1.email.value.match(regex)) {
					return true;
				} else {
					alert("Please enter a valid email address");
					return false;
				}	
			} else {
				alert("Please enter a valid email address");
				return false;
			}
		}
		return false;
	}
} 


function confirmSendManageList(){
	if(theItems == "") {
		return alert("Please add items to your list before sending");
	} else {
		return confirm('Do you want to send your list now?');
	}
}

function setClassAttribute(settingElement, value)
{
	if(settingElement == undefined || value == "")
		return;
	else
	{
		if(navigator.appName == "Microsoft Internet Explorer")
		{
			settingElement.setAttribute('className', value);
		}
		else
		{
			settingElement.setAttribute('class', value);
		}
	}
}

function highlightoption(id) {
	div = document.getElementById('optionheader');
	tags = div.getElementsByTagName('a');
	for(var i=0; i<tags.length; i++) {
		var tagid = tags[i].id;
		setClassAttribute(document.getElementById(tagid), 'normaltext');
	}
	setClassAttribute(document.getElementById(id),'boldtext');
}

function showOptions(option) {
	switch(option) {
		case 'mobile':
			highlightoption('mobile');
			hideDiv('divSendPhone'); hideDiv('divMyPhones'); 
			hideDiv('emailoptions'); hideDiv('divSendSavedEmail'); 
			hideDiv('sharesavedlist');
			hideDiv('divSendEmail'); Effect.Appear('divMyPhones', { duration: 0.8 }); 
			showDiv('mobileoptions'); 
		break;
		case 'email':
			highlightoption('email');
			hideDiv('divSendPhone'); hideDiv('divMyPhones'); 
			hideDiv('divSendEmail'); hideDiv('mobileoptions');
			hideDiv('sharesavedlist');
			Effect.Appear('divSendSavedEmail', { duration: 0.8 }); 
			showDiv('emailoptions'); 
		break;
		case 'share':
			highlightoption('sharethelist');
			hideDiv('mobileoptions'); hideDiv('divSendPhone'); 
			hideDiv('divMyPhones'); hideDiv('emailoptions'); 
			hideDiv('divSendSavedEmail'); 
			hideDiv('divSendEmail');
			Effect.Appear('sharesavedlist', { duration: 0.8 }); 
		break;		
	}
}

function sharelist() {
	var senvars = true;
	box = document.forms[0].selected_list;
	var listid = box.options[box.selectedIndex].value;
	if(listid == null || listid == 'undefined'){
		alert('An error occured. Sorry we are not able to share your list at this time. \nPlease go to saved lists and share it from there.');
		return;
	}
	var f_name = document.getElementById('f_name').value;
	var f_email = document.getElementById('f_email').value;
	if(f_email == 'undefined')
		f_email = '';
	checkDiv = document.getElementById('checkedboxes');
	var checkedMails = '';
	if(checkDiv != null) {
		 inps = checkDiv.getElementsByTagName('input');
		
		for(var i=0; i < inps.length; i++) {
			if(inps[i].checked)
				checkedMails += inps[i].value+'_';
		}
	}
	if(checkedMails == '') {
		if(f_name == '' || f_name == 'undefined') {
			alert("Please enter your friend's name");
			sendvars = false;
		} else if(f_email == '' || f_email == 'undefined') {
			alert("Please enter your friend's email address");
			sendvars = false;
		} else if(f_email.search(/^.+?@.+?\..+$/) < 0) { 
			alert("Please enter a valid email address.");
			sendvars = false;
		}else if((f_email == '' || f_email == 'undefined') && (f_name == '' || f_name == 'undefined')) {
			alert("Please enter a friend's name and email to share your list.");
			sendvars = false;
		} else {
			sendvars = true;
		}
	} else {
		sendvars = true;
	}
	var message = document.getElementById('message').value;
	var emails = f_email+'_'+checkedMails;
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null)
	{
		alert ("Browser does not support HTTP Request");
		return;
	}
	if (xmlHttp.readyState != 0) 
	{
        xmlHttp.abort();
        alert("xmlHttp was aborted because xmlHttp.readyState != 0");
    }
	var url="../Scripts/share_list.php";
	url += "?listid=" + listid;
	url += "&f_name=" + encodeURIComponent(f_name);
	url += "&f_email=" + encodeURIComponent(emails);
	url += "&message=" + encodeURIComponent(message);

	if(sendvars) {
		xmlHttp.open("GET",url,true);
		xmlHttp.onreadystatechange=stateChanged_shareList; 
		xmlHttp.send(null);
	}
}

function stateChanged_shareList() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState == "completed")
	{
		var response = xmlHttp.responseText;
		var statusTxt ='';
		if(response.substr(0,1) == '0') { //success
			statusTxt = response.substr(1, response.length);
			hideDiv('shareme');
			statusDiv = document.getElementById('sharestatus');
			clearInnerHTML(statusDiv);
			var messages = statusTxt.split('_');
			for(var i=0; i<messages.length; i++) {
				if(messages[i] != null && messages[i] != '') {
				statusDiv.appendChild(document.createTextNode(messages[i].substr(3, response.length)));
				statusDiv.appendChild(document.createElement('br'));
				}
			}
			showDiv('sharestatus');
		} else if(response.substr(0,1) == '69') { //success
			statusTxt = response.substr(3, response.length);
			hideDiv('shareme');
			statusDiv = document.getElementById('sharestatus');
			clearInnerHTML(statusDiv);
			var messages = statusTxt.split('_');
			for(var i=0; i<messages.length; i++) {
				if(messages[i] != null && messages[i] != '') {
				statusDiv.appendChild(document.createTextNode(messages[i].substr(3, response.length)));
				statusDiv.appendChild(document.createElement('br'));
				}
			}
			showDiv('sharestatus');
		} else { //fail
			statusTxt = response;
			statusDiv = document.getElementById('sharestatus');
			clearInnerHTML(statusDiv);
			var messages = statusTxt.split('_');
			for(var i=0; i<messages.length; i++) {
				if(messages[i] != null && messages[i] != '') {
				statusDiv.appendChild(document.createTextNode(messages[i].substr(3, response.length)));
				statusDiv.appendChild(document.createElement('br'));
				}
			}
			showDiv('sharestatus');
		}
	}
}

	function showDiv(id) {
		try{
		if (document.getElementById) { // DOM3 = IE5, NS6
				document.getElementById(id).style.display = 'block';
			}
			else {
				if (document.layers) { // Netscape 4
					document.id.display = 'block';
				}
				else { // IE 4
					document.all.id.style.display = 'block';
				}
			}
		}catch(exp) {
			alert(exp+"     "+id);
		}
	}


function hideDiv(id) {
try {
if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.display = 'none';
	}
	else {
		if (document.layers) { // Netscape 4
			document.id.display = 'none';
		}
		else { // IE 4
			document.all.id.style.display = 'none';
		}
	}
	}catch(exp) {
		alert(exp+"  "+id);
	}
}

function showdivlayer(curobj, divID){
	if (document.getElementById){
		var divobj=document.getElementById(divID);
		Effect.Appear('sharefriend', {duration:.3});
		divobj.style.zIndex = 100;				
		centerDiv(divID);
		return true;
	}		
}
function centerDiv(divID){
	var divobj = document.getElementById(divID);	
	var xpos = (document.body.clientWidth/2) - (divobj.offsetWidth)-275;
//	var ypos = ((checkIE().clientHeight)) - (divobj.offsetHeight+25);
	divobj.style.left=xpos+"px";
	//divobj.style.top=ypos+"px";
}

function checkIE(){
	return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
}
function divlayerclose(divobj){
	theDiv = document.getElementById(divobj)
	Effect.Fade('sharefriend', {duration:.2});
	hideDiv('sharestatus');
	showDiv('shareme');
}
