
var debugtxt;
var basehref = "";
var pageData = new Object();
var msgPointer = 0;
var msgArray = ['giftAd','USApparelAd','tdkitsAd','infoAd'];

function getSelectVal(theElem) {
var idx = theElem.selectedIndex;
var val = theElem.options[idx].value
return(val);
}


function setSelectVal(theElem, theVal) {
var numOpts = theElem.options.length;
var i;
var foundOpt = false;
for (i=0;i<numOpts;i++) {
	if (theElem.options[i].value == theVal) {
		theElem.options[i].selected = true;
		foundOpt = true;
	}
}
return(foundOpt);
}



function getRadioVal(theElems) {
var elem;
var val = "";
var idx;
var numElems = theElems.length;

if (numElems > 1) {
	for (idx=0;idx<numElems;idx++) {
		var theElem = theElems[idx];
		if (theElem.checked == true) {
			val = theElem.value;	
		}
	}
} else {
	if (theElems[0].checked == true) {
		val = theElem.value;	
	}
}
return(val);
}

function setRadioVal(theElem, theVal) {
var numOpts = theElem.options.length;
var i;
var foundOpt = false;
for (i=0;i<numOpts;i++) {
	if (theElem.options[i].value == theVal) {
		theElem.options[i].checked = true;
		foundOpt = true;
	}
}
return(foundOpt);
}




function fillTodaysDate(theElem) {
var today = new Date();
var theYear = today.getYear();
if (theYear < 1000) {
	theYear += 1900;
}
var theMonth = (today.getMonth() + 1);
var dateval = (theYear + "-" + theMonth + "-" + today.getDate());
//alert("filling today's date:" + dateval);
theElem.value = dateval;
return(false);
}



function fillCurrentTime(theElem) {
var today = new Date();
var theHour = today.getHours();
var theMinute = (today.getMinutes());
var dateval = (theHour + ":" + theMinute);

theElem.value = dateval;
return(false);
}



function shortDate(theDate) {
var retval = (theDate.getMonth()+1) + "/" + (theDate.getDate()) + "/" + (theDate.getFullYear());
return(retval);
}



function shortUNIXDate(unixDate) {
var edate = parseInt(unixDate);
var thisDate = new Date();
thisDate.setTime(edate * 1000);
var outString = thisDate.getMonth() + "/" + thisDate.getDay() + "/" + thisDate.getFullYear();
return(outString);		
}




function fillFilename(filename, targElem) {
var start = filename.lastIndexOf("/");

if (start < 1) {
        start = filename.lastIndexOf("\\");
}

if (start < 1) {
        start = filename.lastIndexOf(":");
}

var file = filename.substring(start+1,filename.length);
if (file != '') {
        targElem.value = file;
}

}





function writeWindow(windowname, opener, htmltext, params, focus) {
sWindow = window.open('',windowname,params);
sWindow.document.open();
sWindow.document.write(htmltext);
sWindow.document.close();
if (!focus)  opener.focus(); 
if (focus) opener.blur();
return (sWindow);
}

function relocateOpener(targetwindow, newurl) {
targetwindow.document.location.href=newurl;
targetwindow.focus();
return (false);
}

function relocDisplayFrame (theURL) {
//alert("relocating frame to " + theURL);
if (parent.frames['display']) {
	parent.frames['display'].document.location.href = theURL;
} else {
	document.location.href = theURL;
}
return(false);
}

function relocate(targetform, elemname) {
var newloc = "";
var formElem= targetform.elements[elemname];
var idx = formElem.selectedIndex;
var locval = formElem.options[idx].value;
newloc += locval;
if (locval) {
 document.location.href = basehref + newloc;
 return true;
} else {
 return false;
}

}


function popWindow(inWindowname, opener, URL, inParams) {
var defaultParams = "width=740,height=500,scrollbars=yes,menubar=no,location=no,status=yes,resizable";
var defaultWindowname = "Popup Window";
var params;
var windowname;

if (!inParams) {
 params = defaultParams;
} else {
 params = inParams;
}
if (!inWindowname) {
 windowname = defaultWindowname;
} else {
 windowname = inWindowname;
}
var uWindow = window.open(URL,windowname,params);
return(false);
}



function popSendEmail(emailaddress) {
var params = ("width=700,height=400,location,resizable,status");
var theURL = ("mailto:" + emailaddress);
//popWindow = window.open(theURL,'EmailSender',params);
//popWindow.opener = this.window;
//popWindow.close();
document.location.href = theURL;
return (false);
}





// UTILITY FOR GETTING JSDATA FROM A POPUP WINDOW.  
// page_jsdata.html contains an init() function that is called onLoad.
//   the jsdata page calls the function loadJSData(dataArray, dataset, datagroup),
//   passing in the array of data, and the dataset/datagroup requested
//   ** it is the responsibility of this page to the call to loadJSData appropriately for this page context

function dataPop(startHTML, theURL, inParams) {
var defaultParams = "top=0,left=0,screenX=0,screenY=0,fullscreen=yes,scrollbars=no,menubar=0,location=0,status=0";
defaultParams += (",width=" + screen.width);
defaultParams += (",height=" + screen.height);
var windowname = "CustomerDataPop";
var params;

if (!inParams) {
 params = defaultParams;
} else {
 params = inParams;
}

var dataPop;

//dataPop = window.open('/html/eng/man/blank.html',windowname,params);
//dataPop.document.open();
//dataPop.document.write(startHTML);
//dataPop.document.close();
//dataPop.document.location.href = theURL;

dataPop = window.open(theURL,windowname,params);

dataPop.opener = this.window;
}




function fixDecimals(value) {
var rv = value;

//rv = roundAccuracy(value, 2);

rv = oldFixDecimals(rv);
return (rv);

}

/// The following is the old code, which /almost/ worked. ;-)
function oldFixDecimals(value) {
var rv = value;
if (rv == 0) {
	rv = ("0.00");
}
  //alert("starting with: " + rv);
  rv = (rv * 100);
  rv = (rv + .5);
  //alert("parsing " + rv + " for integer value.");
  rv = parseInt(rv);
  //alert("integer value is: " + rv);
  rv = rv / 100;
 
  //alert("float value is: " + rv);

  var rvString = rv.toString();

  //alert("rvString is: " + rvString);

  var idx = rvString.indexOf(".");
  if (idx == (-1)) {
    //alert("decimal not found in rvString: " + rvString);
    rvString = rvString + ".00";
  } else {
    //alert("decimal found in rv: " + rvString);
  	if (idx == (rvString.length-2)) {
    rvString = rvString + "0";
  	}
  }


return(rv);
}

function roundAccuracy(num, accuracy){
	var factor=Math.pow(10,accuracy);
	return Math.round(num*factor)/factor;
}



function confirmWindowClose(msg) {
var retval = true;
var message = "Are you sure you want to close this window?";
if (msg != "") {
	message = msg;
}
retval = confirm(message);
if (retval) {
	if (window.top == window) {
		window.close();
	} else {
		retval = confirm("This window is part of a frameset, Are you sure you want to close the whole frameset?  (cancel to send ONLY THIS FRAME to a blank page)");
		if (retval) {
			top.window.close();
		} else {
			document.location.href = "/html/eng/man/blank.html";
		}
	}
}
return(retval);
}





function closeWindow() {
if (window.top == window) {
	window.close();
} else {
	retval = confirm("This window is part of a frameset, Are you sure you want to close the whole frameset?  (cancel to send ONLY THIS FRAME to a blank page)");
	if (retval) {
		top.window.close();
	} else {
		document.location.href = "/html/eng/man/blank.html";
	}
}
return(retval);
}





function dumpDebug() {
var i;
var theText = "";
for (i in document) {
	theText += (i + "=" + document.i + "<br>\n");
}
writeWindow("theWindow", this.window, theText);
}



function toggleCanvas(canvasName, checkedState) {
var targetCanvas = document.getElementById("canvas" + canvasName);
if (checkedState == true) {
        var sourceCanvas = document.getElementById("source" + canvasName);
        targetCanvas.innerHTML = sourceCanvas.innerHTML;
} else {
        targetCanvas.innerHTML = "";
}
return(false);
}



function showInlineMessage(messageName, canvasName) {
var messageSource = (messageName + "Source");
var messageTarget = "";
if (canvasName) {
	messageTarget = canvasName;
} else {
	messageTarget = "inlineMessageCanvas";
}
var hideMessage = ("<div align=\"center\"><a href=\"#\" onClick=\"return showInlineMessage('blank', '" + messageTarget + "');\" style=\"font-size:10px;\">Hide This Message</a></div>");
var target = document.getElementById(messageTarget);
var source = document.getElementById(messageSource);
if (messageName == "blank") {
	target.innerHTML = "";
} else {
	target.innerHTML = source.innerHTML + hideMessage;
}
return(false);
}


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 pricePerUnit(price, numunits, unittype)
{
	var price = parseFloat(price);
	var numunits = parseFloat(numunits);
	var unittype = unittype;
	
	var priceperunit = price / numunits;
	priceperunit = priceperunit.toFixed(2);
	
	return (priceperunit + "/" + unittype);
}



function locateElement(obj) {
	var elemleft = elemtop = 0;
	
	if (obj.offsetParent) {
		do {
			elemleft += obj.offsetLeft;
			elemtop += obj.offsetTop;
		} while (obj = obj.offsetParent);	// Check offset while parent exists
		
		//alert(elemleft + "," + elemtop)
		
		return [elemleft, elemtop];
	}
}
	



function showTopMessage(msgName)
{       
	if (getCookie('msgDismissed') != null) return;
	if (getCookie(msgName) != null) {
		msgPointer++;
		if (msgArray[msgPointer]) {
			return showTopMessage(msgArray[msgPointer]);
		}
		else return;
	}
	
	var elem = document.getElementById('messageSpace');
	var out = "";
	
	out += ("<div id=\"oneTimeMsg\" style=\"margin-bottom:4px;margin-top:-10px;padding-left:10px;\">");
	out += createTopMessageHTML(msgName);
	out += ("</div>");
	        
	elem.innerHTML = out;
}


function createTopMessageHTML(msgName)
{       var adHTML = "";
        var messageText = new Array;
        var messageURL = new Array;
		messageText['giftAd'] = ("http://images.dharmatrading.com/images/public/notification/free_gift.png");
		messageURL['giftAd'] = ("/freegift");
		messageText['USApparelAd'] = ("http://images.dharmatrading.com/images/public/notification/american_apparel.png");
		messageURL['USApparelAd'] = ("/products/american_apparel.html");
		messageText['tdkitsAd'] = ("http://images.dharmatrading.com/images/public/notification/tie_dyekits.png");
		messageURL['tdkitsAd'] = ("/kits/tie-dye.html");
		messageText['infoAd'] = ("http://images.dharmatrading.com/images/public/notification/info_page.png");
		messageURL['infoAd'] = ("/info");

        adHTML += ("<a class=\"x_remove right\" style=\"font: normal bold 9px/22px Arial; color: #666; position: relative; top: 18px; right: 20px;\" href=\"javascript:dismissTopMessage(\'" + msgName + "\')\" title=\"Dismiss this note\">X</a>");
        adHTML += ("<a href=\"" + messageURL[msgName] + "\">");
        adHTML += ("<img src=\"" + messageText[msgName] + "\" border=\"0\" /></a>");

        return adHTML;
}


function dismissTopMessage(msgName)
{       var elem = document.getElementById('messageSpace');
        elem.innerHTML = "";
        var expireDate = new Date();
        var expireDateDaily = new Date();
        expireDate.setDate(expireDate.getDate()+3000);
        expireDateDaily.setDate(expireDateDaily.getDate()+1);
        document.cookie = (msgName + "=closed; path=/; expires=" + expireDate.toGMTString());
        document.cookie = ("msgDismissed=dismissed; path=/; expires=" + expireDateDaily.toGMTString());
}




function getXMLHttpRequest()
{
   if (window.XMLHttpRequest) {
       return new XMLHttpRequest();
   } else if (window.ActiveXObject) {
       var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0",
               "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
               "Microsoft.XMLHTTP"];

       for (var i=0; i < arrSignatures.length; i++) {
           try {

               var oRequest = new ActiveXObject(arrSignatures[i]);

               return oRequest;

           } catch (oError) {
               //ignore
           }
       }
   }

   return null;
}






function sendAjaxPOST(url, vars, callbackFunction) {
//alert("Sending review to: " + url);

var request = getXMLHttpRequest();

request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 

request.onreadystatechange = function(){

		if (request.readyState == 4 && request.status == 200) {

				if (request.responseText){

						callbackFunction(request.responseText);
				}
		}
}
request.send(vars);

}



function sendAjaxGET(url, callbackFunction) {
//alert("Sending review to: " + url);

var request = getXMLHttpRequest();
var vars = "";
request.open("GET", url, true);

request.onreadystatechange = function(){

		if (request.readyState == 4 && request.status == 200) {

				if (request.responseText){

						callbackFunction(request.responseText);
				}
		}
}
request.send(vars);

}





function sendAjaxGETXML(url, callbackFunction) {
//alert("Sending review to: " + url);

var request = getXMLHttpRequest();

request.open("GET", url, true);
var vars = "";
request.onreadystatechange = function(){

                if (request.readyState == 4 && request.status == 200) {

                                if (request.responseText){

                                                callbackFunction(request.responseXML);
                                }
                }
}
request.send(vars);

}



function sendAjaxXML(url, vars, callbackFunction) {

var request = getXMLHttpRequest();

request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 

request.onreadystatechange = function(){

		if (request.readyState == 4 && request.status == 200) {

				if (request.responseXML){

						callbackFunction(request.responseXML);
				}
		}
}
request.send(vars);

}




function scriptMessage(msgText) {
var theElem = document.getElementById('scriptMessage');
theElem.innerHTML = msgText;
}


function selectRandomComment() {
	if (document.getElementById('randomBlock')) {
		var headID = document.getElementsByTagName("head")[0];         
		var newScript = document.createElement('script');
		newScript.type = 'text/javascript';
		newScript.src = '/cgi-bin/customercomments.pl?jsonp=parseCustomerCommentJSON';
		headID.appendChild(newScript);
	}
}




function getCustomerComment(commentListData) {
	var arrayIndex = 0;
	var commentId = 0;
	var numComments = 0;
	var listArray = new Array;
	var commentsArray = new Array;

	if (document.getElementById('randomBlock')) {
		if (commentListData) {
			listArray = commentListData.getElementsByTagName("item");
			numComments = listArray.length;
			arrayIndex = Math.round(numComments * Math.random());
			commentId = listArray[arrayIndex].getAttribute("id");
			var theURL = ("/xml/customercomments/" + commentId + ".xml");
			var tempString = ("<div align=\"left\" valign=\"middle\" style=\"color:#FFFDC2;;\">http://www.dharmatrading.com" + theURL + "</div>");
			var displayCanvas = document.getElementById('randomBlock');
			displayCanvas.innerHTML = tempString;
			sendAjaxGETXML(theURL, parseCustomerCommentXML);
			
			var tempString = ("<div align=\"left\" valign=\"middle\" style=\"color:#FFFDC2;;\">http://www.dharmatrading.com" + theURL + "</div>");
			var displayCanvas = document.getElementById('randomBlock');
			displayCanvas.innerHTML = tempString;
		}
	}
}


function parseCustomerCommentXML(xmlData) {
	var theComment = new Object();
	var listArray = xmlData.getElementsByTagName("item");
	var obj = listArray[0];
	theComment['firstname'] = obj.getAttribute('firstname');
	theComment['lastname'] = obj.getAttribute('lastname');
	theComment['cdate'] = obj.getAttribute('cdate');
	if (browserName == "Microsoft Internet Explorer") {
		theComment['comments'] = obj.childNodes[0].childNodes[0].text;
	}
	else {
		theComment['comments'] = obj.childNodes[0].childNodes[0].nodeValue;
	}
	showCustomerComment(theComment);
}


function parseCustomerCommentJSON(JSONData) {
var theComment = eval(JSONData);
showCustomerComment(theComment);
customerCommentJSONActive = true;
}


function showCustomerComment(theComment) {
var outString = ("<div align=\"center\" style=\"max-width:100%;\"><div align=\"left\" style=\"font-style:italic;color:#000000;margin-left:30px;margin-top:12px;\">");
var displayCanvas = document.getElementById('randomBlock');

outString += ("\"");
outString += (theComment['comments']);
outString += ("\" <br />");
outString += ("<b>-" + theComment['firstname'] + "&nbsp;" + theComment['lastname'] + "</b><br />");
var dateAdded = new Date();
dateAdded.setTime(theComment['cdate']*1000); // Customer comment creation date
outString += (dateAdded.toDateString() + "</a></div></div>");
displayCanvas.innerHTML = outString;


}





function sendAjaxGETXML(url, callbackFunction) {
//alert("Sending review to: " + url);

var request = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0");

request.open("GET", url, true);
var vars = "";
request.onreadystatechange = function(){

		if (request.readyState == 4 && request.status == 200) {

				if (request.responseText){

						callbackFunction(request.responseXML);
				}
		}
}
request.send(vars);

}

function getXMLDataURL(objid){
var xmlURL = ("/xml/products/" + objid.substring(objid.length-4, objid.length-3) + "/" + objid + ".xml");
return(xmlURL);
}



/*  Kits  */
function showKitContents(objid) {
	var theURL = ("http://" + sslServer + sslDomain + getXMLDataURL(objid));
	sendAjaxGETXML(theURL, displayKitContents);
}

function displayKitContents(xmlData) {
	var productData = parseProductData(xmlData.getElementsByTagName("productdata")[0]);
	var canvas = document.getElementById("canvasKitContents" + productData['objid']);
	try {
		canvas.innerHTML = "Kit Contents:<br/>" + getKitContentsHTML(eval('(' + productData['kitconfig'] + ')'));
	} catch (err) {
		//alert("Error: cannot find canvas for objid " + productData['objid']);
	}
}

function getKitContentsHTML(kitconfig) {
var i;
var outString = "";
for (i in kitconfig) {
	var item = kitconfig[i];
	outString += ("<div>" + item.quantity + " @ ");
	outString += (item.title);
	outString += ("</div>");
}
return(outString);
}

function parseProductData(theItem) {
	var d = {};
	var attrIdx = 0;
    if (theItem.attributes) {
		var attrList = theItem.attributes;
		for (attrIdx = 0; attrIdx < attrList.length; attrIdx++) {
			d[attrList.item(attrIdx).name] = attrList.item(attrIdx).value;
		}
	}
	var nodeIdx = 0;
    if (theItem.childNodes) {
		for (nodeIdx = 0; nodeIdx < theItem.childNodes.length; nodeIdx++) {
			var topNode = theItem.childNodes[nodeIdx];
			var nodeName = topNode.nodeName;
			if ( (nodeName == "images") || 
					(nodeName == "thumbs") || 
					(nodeName == "promoimgs") || 
					(nodeName == "linkages") || 
					(nodeName == "variants") ) {
				// Deal with sub-nodes
				d[nodeName] = new Array();
				var subnodeIdx = 0;
				for (subnodeIdx = 0; subnodeIdx < topNode.childNodes.length; subnodeIdx++) {
					var subNode = topNode.childNodes[subnodeIdx];
					if (subNode.attributes) {
						var attrList = subNode.attributes;
						for (attrIdx = 0; attrIdx < attrList.length; attrIdx++) {
							var subObject = {};
							subObject[attrList.item(attrIdx).name] = attrList.item(attrIdx).value;
							d[nodeName].push(subObject);
						}
					}
				}
			} else {
				var nodeText = getNodeText(theItem.childNodes[nodeIdx]);
				if (nodeText) {
					d[nodeName] = nodeText;
				}
			}
		}
	}
	
	//scriptMessage(JSON.stringify(d));
return(d);
}




function getNodeText(theNode) {
var outText;
if (browserName == "Microsoft Internet Explorer") {
	outText = theNode.text;
}
else {
	outText = theNode.textContent;
}
return(outText);
}



function setupHexColorChips() {
	
	$("#resize_chips").click(function() {
		var big = $(".rgbchip").hasClass('rgblarge');
		if (big) {
			$(".rgbchip").removeClass('rgblarge');
			$("#resize_chips").html('Bigger Colorchips&nbsp;[+]');
		}
		else {
			$(".rgbchip").addClass('rgblarge');
			$("#resize_chips").html('Smaller Colorchips&nbsp;[-]');
		}
	});
	
	$(".rgbchip").click(function() {
		var rgb = $(this).css("background-color");
		$.facebox('<div style="background-color:' + rgb + ';width:500px;height:300px;border:2px solid #cccccc;"></div>');
	});
}


function initTinyMCE() {

tinyMCE.init({
	mode : "specific_textareas",
	theme : "advanced",
	theme_advanced_toolbar_location : "top",
	editor_selector : "mceEditor",
    content_css : "/css/classes.css",
	plugins : "table,style,media,advlink,advimage",
	theme_advanced_buttons1_add : "styleprops",
	theme_advanced_buttons3_add : "tablecontrols,media",
	convert_urls : false,
	table_inline_editing : true,
	table_styles : "Header 1=header1;Header 2=header2;Header 3=header3",
	table_cell_styles : "Header 1=header1;Header 2=header2;Header 3=header3;Table Cell=tableCel1",
	table_row_styles : "Header 1=header1;Header 2=header2;Header 3=header3;Table Row=tableRow1",
	table_cell_limit : 1000,
	table_row_limit : 500,
	table_col_limit : 500,
	inline_styles : true

});


tinyMCE.init({
	mode : "specific_textareas",
	theme : "advanced",
	theme_advanced_toolbar_location : "top",
	editor_selector : "mceEditorBasic",
    content_css : "/css/classes.css",
	plugins : "style",
	theme_advanced_disable : "justifyleft,justifyright,justifycenter,justifyfull,undo,redo,separator,strikethrough,cleanup",
	theme_advanced_buttons3_add : "styleprops",
	convert_urls : false,
	table_inline_editing : true,
	table_styles : "Header 1=header1;Header 2=header2;Header 3=header3",
	table_cell_styles : "Header 1=header1;Header 2=header2;Header 3=header3;Table Cell=tableCel1",
	table_row_styles : "Header 1=header1;Header 2=header2;Header 3=header3;Table Row=tableRow1",
	table_cell_limit : 1000,
	table_row_limit : 500,
	table_col_limit : 500
});

}


