// constants
var C_handlerPage = "/a.php";

var C_msgDiv = "aMsg";
var C_actionDiv = "actionDiv";
var C_pickListDiv = "pickList";

// instance
var iConfObj = null;
var i_imgurl = null;

var ipinxPrice = null;
var ipinxTitle = null;
var ipinxUrl = null;


// generic functions

function ge(elem) {
	return document.getElementById(elem).value;
}

function gobj(elem) {
	return document.getElementById(elem);
}

function hide(name){
	tObject = document.getElementById(name);
	hideObj(tObject);
}
function hideObj(tObject){
	tObject.style.visibility = "hidden";
	tObject.style.height = "0px";
	tObject.style.width = "0px";
	tObject.style.position = "absolute";
}

function executeNoResponseHtml(serverPage, msg, afterEventAction) {
	execute(null, serverPage, msg, afterEventAction);
}

function execute(responseObjId, serverPage, msg, afterEventAction) {
	
	if (msg != null) showMsg(msg);
//	hideMsg();
//	return false;

	//Create a boolean variable to check for a valid Internet Explorer instance.
	var xmlhttp = false;
	
	//Check if we are using IE.
	try {
		//If the javascript version is greater than 5.
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		//If not, then use the older active x object.
		try {
			//If we are using Internet Explorer.
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
			//Else we must be using a non-IE browser.
			xmlhttp = false;
		}
	}
	//If we are using a non-IE browser, create a javascript instance of the object.
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		xmlhttp = new XMLHttpRequest();
	}
	
	var responseObj = null;
	if (responseObjId != null) {
		responseObj = document.getElementById(responseObjId);
	}
//	alert(serverPage);
	xmlhttp.open("GET", serverPage);
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			if (responseObj != null) responseObj.innerHTML = xmlhttp.responseText;
			hideMsg();
			afterExecuteEvent(afterEventAction);
		}
	}
	xmlhttp.send(null);
}

function afterExecuteEvent(afterEventActionAction) {

	if (afterEventActionAction == null) return;

	if (afterEventActionAction == "gotoURL") {
		showMsg("taking you back ...");
		window.location = iGotoURL;
	}

	if (afterEventActionAction == "tweetConf") {
		msg = "We received your message and will publish it after approval.";
		msg += '<p><A href="javascript:void(0);" onClick="hide(\''+C_actionDiv+'\');">Close Window</a>';

		showDiv(110,250,C_actionDiv,msg,true,"Thanks!");

	}
	if (afterEventActionAction == "confirmRate") {
		msg = "Thanks! Your review is now pending approval and will be published soon!";
		msg += '<p><A href="javascript:void(0);" onClick="hide(\''+C_actionDiv+'\');hide(\'ratingDIV\');">Close Window</a>';

		showDiv(110,250,C_actionDiv,msg,true,"Thanks!");
		

	}
	if (afterEventActionAction == "qConf") {
		msg = "We received your question and will reply as soon as possible.";
		msg += '<p><A href="javascript:void(0);" onClick="hide(\''+C_actionDiv+'\');">Close Window</a>';

		showDiv(110,250,C_actionDiv,msg,true,"Thanks!");

	}

	if (afterEventActionAction == "confirmUpdate") {
		confBox = document.getElementById(iConfObj);
		confBox.innerHTML = 'updated!';
	}

	if (afterEventActionAction == "refreshListCnt") {

		// refresh lists due to (count) - javascript update on DIV: increment new, decrement current (unless ALL)
		needRefresh = false;
//		needRefresh = true;
		if (iSourceListId > 0) needRefresh = changeListCnt("listCnt"+iSourceListId, -1);
		if (iTargetListId > 0) needRefresh = (needRefresh || changeListCnt("listCnt"+iTargetListId, 1));

		if (needRefresh) {
			serverPage = assemblePage("getList", null);
			execute(C_listsDiv, serverPage, "please wait ...", null);
		}

		// hide row
		if (iRowToHideDivId != null) hide(iRowToHideDivId);

	}
	if (afterEventActionAction == "showListDetail") {
		showListDetail(iListId);
	}
}

function getBrowserHeight() {                                         
	var intH = 0;                                                   
	var intW = 0;                                                   
								   
	if(typeof window.innerWidth  == 'number') {                     
		intH = window.innerHeight;                                   
		intW = window.innerWidth;                                    
	}                                                               
	else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		intH = document.documentElement.clientHeight;              
		intW = document.documentElement.clientWidth;               
    }                                                               
    else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {                                            
		intH = document.body.clientHeight;                            
		intW = document.body.clientWidth;                             
    }                                                               
                                                                           
    return {width: parseInt(intW), height: parseInt(intH)};         
}                                                                   

function showMsg(msg) {
	hm = 50;
	wm = 180;
	showDiv(hm,wm,C_msgDiv,msg,false,null);
}
                                                                           
function showDiv(hm,wm,divId,content,alignLeft, title) {

	if (alignLeft) {
		aln = 'left';
	}
	else {
		aln = 'center';
	}

	titleDisp = "";
	if (title != null) titleDisp = "<span class='actionDivTitle'>"+title+"</span><p>";
	if (content != null) {
		content = '<table width="100%"><tr><td align="'+aln+'">'+titleDisp+content+'</td></tr></table>';
	}
	var bws = getBrowserHeight();                                   
								   
//	hs = screen.height; 
//	ws = screen.width;
	hs = bws.height;
	ws = bws.width;
//	alert("hs="+hs+ "  ws=" + ws);
	scrollTop = 100;
	topOffset = 0;

	if(bType.ie) {
		//scrollTop = document.body.scrollTop;
		//topOffset = -30; // this is the position of the H1 tag from the top of the screen
	}
	posTop = scrollTop + parseInt((hs - topOffset - hm) / 2) - 150;
	posLeft = parseInt((ws - wm) / 2);

	theObject = document.getElementById(divId);
	if (alignLeft) {
		theObject.style.textAlign = 'left';
	}
	else {
		theObject.style.textAlign = 'center';
	}
	theObject.style.height = hm + "px";
	theObject.style.width = wm + "px";
	theObject.style.top = posTop + "px";
	theObject.style.left = posLeft + "px";

	if (bType.ie) {
		theObject.style.position = "absolute";
	}
	else {
		theObject.style.position = "fixed";
	}

	if (content != null) theObject.innerHTML = content;
	theObject.style.visibility = "visible";

}

function showHiddenDiv(divId, hm, wm) {

	theObject = document.getElementById(divId);
	theObject.style.height = hm + "px";
	theObject.style.width = wm + "px";
	theObject.style.visibility = "visible";
	theObject.style.position = "relative";

}

function hideMsg() {
	hide(C_msgDiv);
}

function assemblePage(action, tok, p1, v1, p2, v2, p3, v3, p4, v4, p5, v5, p6, v6, p7, v7) {
	return assemblePage2(C_handlerPage, action, tok, p1, v1, p2, v2, p3, v3, p4, v4, p5, v5, p6, v6, p7, v7);
}



function assemblePage2(pageHandler, action, tok, p1, v1, p2, v2, p3, v3, p4, v4, p5, v5, p6, v6, p7, v7) {
	uauth = "";
	if (document.getElementById('uauth') != null) uauth = document.getElementById('uauth').value;
	p = pageHandler + "?action=" + action + "&uauth=" + uauth;
	if (tok != null) p += "&tok=" + tok; 
	if (p1 != null) p += "&" + p1 + "=" + escape(v1); 
	if (p2 != null) p += "&" + p2 + "=" + escape(v2); 
	if (p3 != null) p += "&" + p3 + "=" + escape(v3); 
	if (p4 != null) p += "&" + p4 + "=" + escape(v4); 
	if (p5 != null) p += "&" + p5 + "=" + escape(v5); 
	if (p6 != null) p += "&" + p6 + "=" + escape(v6); 
	if (p7 != null) p += "&" + p7 + "=" + escape(v7); 
	p += "&" + Math.random();
	return p;
}

//	business functions

function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
	  retValue = retValue.substring(1, retValue.length);
	  ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
	  retValue = retValue.substring(0, retValue.length-1);
	  ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
	  retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function


function showInputWnd(prompt, label, returnFunction){

	var cnt = "";
	cnt += '<form><b>'+label+':</b>&nbsp;&nbsp;<input ass=field type="text" id="inDiv" name="inDiv"></form>';
	cnt += '<p>';
	cnt += '<IMG onClick="val = ge(\'inDiv\');if (validateInputText(val)) {hide(\''+C_actionDiv+'\');'+returnFunction+'(val)}" SRC="images/continue.png" BORDER="0" >';
	cnt += '&nbsp;&nbsp;<IMG onClick="hide(\''+C_actionDiv+'\');" SRC="images/cancel.gif" BORDER="0" >';

	showDiv(120,280,C_actionDiv,cnt,true,prompt);
}


function validateInputText(val) {
	if (trim (val) == "") return false;
	return true;
}


function toBool01(bstr) {
	var b = 1;
	if(bstr == false) b = 0;
	return b;
}


function validateEmail(email) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if(reg.test(email) == false) {
		alert('Invalid Email Address');
		return false;
	}
	return true;
}


function sendFeedbackWnd() {
	var cnt = "";
	
	cnt += '<form><table>';
	
	cnt += '<tr><td><b>Your Message:</b></td></tr><tr><td><TextArea class=field id="ecmt" name="ecmt" cols=72 rows=5></TextArea></td></tr>';

	cnt += '</table></form>';

	// button
	cnt += '<p>';
	cnt += '<IMG onClick="cmt = ge(\'ecmt\');hide(\''+C_actionDiv+'\');sendFeedback(cmt)" SRC="images/send.gif" BORDER="0" >';
	
	// cancel
	cnt += '&nbsp;&nbsp;<IMG onClick="hide(\''+C_actionDiv+'\');" SRC="images/cancel.gif" BORDER="0" >';

	showDiv(190,400,C_actionDiv,cnt,true,"Send us your feedback!");
}


function sendFeedback(cmt) {
	serverPage = assemblePage("sendFeedback", null, "cmt", cmt);
	executeNoResponseHtml(serverPage, "sending feedback ...", null);
}

function sendMsg(cmt, em) {
	serverPage = assemblePage("sendQ", null, "q", cmt, "em", em);
	executeNoResponseHtml(serverPage, "sending question ...", "qConf");
//	execute("dbg", serverPage, "sending question ...", null);
}

function sendQ(cmt, em, name, subj) {
	serverPage = assemblePage("sendQA", null, "q", cmt, "em", em, "subj", subj, "name", name);
	executeNoResponseHtml(serverPage, "sending question ...", "qConf");
//	execute("dbg", serverPage, "sending question ...", null);
}

function adminAddProd(asin, descr, imgurl) {
	serverPage = assemblePage("adminAddProd", null, "asin", asin, "descr", descr, "imgurl", imgurl);
	executeNoResponseHtml(serverPage, "adding product ...", null);
//	execute("dbg", serverPage, "adding prod ...", null);
}

function adminAddSplash(title, catid) {
//	alert(i_imgurl);
	serverPage = assemblePage("adminAddSplash", null, "imgurl", i_imgurl, "title", title, "catid", catid);
	executeNoResponseHtml(serverPage, "adding splash ...", null);
//	execute("dbg", serverPage, "adding splash ...", null);
}

function adminAddSplashWin(imgurl) {
	var cnt = "";
	
	i_imgurl = imgurl;
	cnt += '<form><table>';
	
	cnt += '<tr><td><b>Title</b></td></tr><tr><td><INPUT type=TEXT class=field id="etit" name="etit" size=80></td></tr>';
	cnt += '<tr><td><b>Target Cat ID</b></td></tr><tr><td><INPUT type=TEXT class=field id="ecat" name="ecat" size=5></td></tr>';

	cnt += '</table></form>';

	// button
	cnt += '<p>';
	cnt += '<a href="javascript:void(0);" onClick="tit = ge(\'etit\');cat = ge(\'ecat\');hide(\''+C_actionDiv+'\');adminAddSplash(tit,cat)">OK</A>';
	
	// cancel
	cnt += '&nbsp;&nbsp;<A href="javascript:void(0);" onClick="hide(\''+C_actionDiv+'\');">Cancel</a>';

	showDiv(190,400,C_actionDiv,cnt,true,"Add to Splash");
}

function adminDelProd(prodid) {
	rowId = "row" + prodid;
	serverPage = assemblePage("adminDelProd", null, "prodid", prodid);
	executeNoResponseHtml(serverPage, "deleting product ...", null);
	hide(rowId);

//	execute("dbg", serverPage, "adding prod ...", null);
}


function adminDelSplash(id) {
	rowId = "row" + id;
	serverPage = assemblePage("adminDelSplash", null, "splashid", id);
	executeNoResponseHtml(serverPage, "deleting ...", null);
//	execute("dbg", serverPage, "deleting ...", null);
	hide(rowId);

}

function showBrowseNodes(nodeid, copyTo, nextparentid, parentid, sIdx, catId ) {
//	showDiv(hm,wm,divId,content,alignLeft, title) {
	showDiv(600,500,C_pickListDiv,"",true, "");
	serverPage = assemblePage("getBrowseNodes", null, "nodeid", nodeid, "copyTo", copyTo, "parentid", parentid, "nextparentid", nextparentid, "sIdx", sIdx, "catId", catId);
	execute(C_pickListDiv, serverPage, "please wait ...", null);

}

function addSubNodes(nodeid, sIdx, catId ) {
	serverPage = assemblePage("addSubNodes", null, "nodeid", nodeid, "sIdx", sIdx, "catId", catId);
	execute("dbg", serverPage, "adding all sub-categories ...", null);

}

function createCat(sIdx, catId, amzNode, name) {
	serverPage = assemblePage("createCat", null, "sIdx", sIdx, "catId", catId, "amzNode", amzNode, "name", name);
	executeNoResponseHtml(serverPage, "adding category ...", null);
	//execute("dbg", serverPage, "adding category ...", null);

}


function pinx(title, prc, url) {
	var cnt = "";

	ipinxUrl = url;
	ipinxTitle = title;
	ipinxPrice = prc;
	
	cnt += "Price drop alerts are powered by Price!pinx.<p>";
	cnt += '<form>';
	
	cnt += '<b>Your email address (for alerts only):</b><br><INPUT type=TEXT class=field id="em" name="em" size=50>';

	cnt += '</form>';

	// button
	cnt += '<p>';
	cnt += '<a href="javascript:void(0);" onClick="em = ge(\'em\');hide(\''+C_actionDiv+'\');pinxSave(em, ipinxTitle, ipinxPrice, ipinxUrl)">Send me Alerts for this product</A>';
	
	// cancel
	cnt += '&nbsp;&nbsp;<A href="javascript:void(0);" onClick="hide(\''+C_actionDiv+'\');">Cancel</a>';

	cnt += '<p><hr><p>Price!pinx allows you to request free price drop alerts for any product on almost any retailer’s website. <a target=_new href="http://www.pricepinx.com/intro.php">Learn more!</a><p><div align=center style="background-color: white"><a target=_new href="http://www.pricepinx.com/intro.php"><img src="/images/spacer.gif" border=0 height=10 width="100%"><img src="http://www.pricepinx.com/images/logo24.png" border=0 ></a><img src="/images/spacer.gif" border=0 height=10 width="100%"></div>';

	showDiv(360,380,C_actionDiv,cnt,true,"Create Price Drop Alerts for this Product!");
}

function sendMsgWnd() {
	var cnt = "";

	
	cnt += "Ask us and get answers - guaranteed! <p>";
	cnt += '<form>';
	
	cnt += '<b>Your email address (*):</b><br><INPUT type=TEXT class=field id="em" name="em" size=50>';
	cnt += '<p><b>Your Question:</b><br><TextArea class=field id="qu" name="qu" cols=65 rows=5></TextArea>';

	cnt += '</form>';

	// button
	cnt += '<p>';
	cnt += '<a href="javascript:void(0);" onClick="em = ge(\'em\');qu = ge(\'qu\');hide(\''+C_actionDiv+'\');sendMsg(qu, em)">Send</A>';
	
	// cancel
	cnt += '&nbsp;&nbsp;<A href="javascript:void(0);" onClick="hide(\''+C_actionDiv+'\');">Cancel</a>';


	showDiv(300,580,C_actionDiv,cnt,true,"Ask a Question");
}

function sendQaWnd() {
	var cnt = "";

	
	cnt += "Ask us and get answers - guaranteed! <p>";
	cnt += '<form>';
	
	cnt += '<b>Your email address (*):</b><br><INPUT type=TEXT class=field id="em" name="em" size=50>';
	cnt += '<p><b>Your name (*):</b><br><INPUT type=TEXT class=field id="name" name="name" size=50>';
	cnt += '<p><b>Subject (*):</b><br><INPUT type=TEXT class=field id="subj" name="subj" size=50>';
	cnt += '<p><b>Your Question:</b><br><TextArea class=field id="qu" name="qu" cols=65 rows=5></TextArea>';

	cnt += '</form>';

	// button
	cnt += '<p>';
	cnt += '<a href="javascript:void(0);" onClick="em = ge(\'em\');subj = ge(\'subj\');name = ge(\'name\');qu = ge(\'qu\');hide(\''+C_actionDiv+'\');sendQ(qu, em, name, subj)">Send</A>';
	
	// cancel
	cnt += '&nbsp;&nbsp;<A href="javascript:void(0);" onClick="hide(\''+C_actionDiv+'\');">Cancel</a>';


	showDiv(380,550,C_actionDiv,cnt,true,"Ask a Question");
}

function getEm(subj) {
	var cnt = "";

	
	cnt += 'Please send email to <a href="mailto:get10@ecigarettes365.com?subject='+subj+'">get10@ecigarettes365.com</a>!';
	// button
	cnt += '<p>';
	
	// done
	cnt += '<A href="javascript:void(0);" onClick="hide(\''+C_actionDiv+'\');">Close Window</a>';

	showDiv(150,300,C_actionDiv,cnt,true,"Send Email");
}

function pinxSave(email, title, price, url) {
	//alert(title);
	serverPage = assemblePage("pinx", null, "email", email, "title", title, "price", price, "url", url);
	executeNoResponseHtml(serverPage, "registering your price drop alert request ...", null);
	//execute("dbg", serverPage, "registering your price drop alert request ...", null);

}

function sendtweetForApproval(st) {
	serverPage = assemblePage("tweet", null, "msg", st);
	executeNoResponseHtml(serverPage, "sending your message ...", "tweetConf");
//	execute("dbg", serverPage, "DBG: sending your message ...", "tweetConf");
}

function shareApprove(app, id) {
	serverPage = assemblePage("tweetApprove", null, "app", app, "id", id);
//	executeNoResponseHtml(serverPage, "processing ...", null);
	execute("dbg", serverPage, "processing ...", null);
}

function rateInsert(txt, model, rname, page, r1, r2, r3) {
	serverPage = assemblePage("rate", null, "txt", txt, "model", model, "rname", rname, "page", page, "r1", r1, "r2", r2, "r3", r3);
	executeNoResponseHtml(serverPage, "saving ...", "confirmRate");
//	execute("dbg", serverPage, "processing ...", null);
}