/* copyright 2005 One Mile Up, Inc. You may NOT copy, modify, and distribute
*  this file, without proper licensing from the copyright holder.
*  This file is provided "AS-IS" without warranties of any kind, including any
*  implied warranties.
*
*  jshow.js
*  Initial Author and Architect:  Andres Toussaint
*
*/

var config;
var categories;
var elements;
var elementObject;
var catSel, elemSel;
var categoryDiv, elementDiv, detailDiv;
var numOfLines = 8;
var rowHeight = 29;
var mousedown = false;

var style_base = "font-size:10px;line-height:14px;"
				+"font-family:Verdana, Geneva, Arial, sans-serif;text-align:left;"
				+"text-indent:5px;padding:1px;width:99%;overflow:hidden;";

var style_list = style_base + "color: black;background-color:#f5fffa;";
var style_listSel = style_base + "color: white;;background-color:#333333;";
var style_listRoll = style_base + "color: #333333;background-color:#ADD8E6;";

//--------initShow -------------
function initShow() {

	categoryDiv = document.getElementById("categories");
	elementDiv = document.getElementById("elements");
	detailDiv = document.getElementById("detail");	
	loadXML("a_milphPromo/xml/config.xml", loadList);
}

//-------- loadList -------------
function loadList(xmldoc, url) {
	if (xmldoc.readyState == 4) {
		config = xmldoc.responseXML.getElementsByTagName("config");
		
		
		loadXML("a_milphPromo/xml/"+ config[0].getAttribute("categories"), populateCategories);
	}
}

//-------- populateCategories -------------
function populateCategories(xmldoc, url) {

if (xmldoc.readyState == 4) {
	categories = xmldoc.responseXML.getElementsByTagName("category");
	/*
	var newRange = document.createRange();
	newRange.selectNodeContents(categoryDiv);
	newRange.deleteContents();
	*/
	while(categoryDiv.hasChildNodes()) {
		categoryDiv.removeChild(categoryDiv.firstChild);
	}
	
	for (var i=0; i < categories.length; i++) {
		var c = categories[i];
		var value = c.getAttribute("name");
		var listDiv  = document.createElement("div");
		listDiv.setAttribute("id", value);
		listDiv.setAttribute("position","");
		listDiv.style.cssText = style_list;
		listDiv.setAttribute("onmouseover","listRollOver(this)");
		listDiv.setAttribute("onmouseout","listRollOut(this)");
		listDiv.setAttribute("onclick","listClick(this)");
		try {
		//If we are in IE, need to attach events
        listDiv.attachEvent( "onmouseover", ie_dispatcher);
        listDiv.attachEvent( "onmouseout", ie_dispatcher);
        listDiv.attachEvent( "onclick", ie_dispatcher);
        } catch (ex) {}
        
        
		listDiv.appendChild(document.createTextNode(value));
		categoryDiv.appendChild(listDiv);
	}
}
}

function ie_dispatcher() {
	var theAttr = event.srcElement;

	if (event.srcElement.tagName != "DIV") {
		theAttr = locateParentDiv(event.srcElement);
	} 

	while(theAttr.getAttribute("on"+event.type) == null) {
	try {
		theAttr = theAttr.parentNode;
	} catch (error) {
		return;
	}
		
	}
	
	var handler = theAttr.getAttribute("on"+event.type);
	handler = handler.substring(0, handler.indexOf('('));
	var theFunction = window[handler];
	theFunction(theAttr);
}

function locateParentDiv(child) {
	var parent = child.parentNode;
	while (parent.tagName != "DIV" ) {
		parent = parent.parentNode;
	}
	return parent;
}


//-------- listClick -------------
function listClick(target) {
	if (catSel != null) {
		catSel.style.cssText = style_list + catSel.getAttribute("position");
		
	}
	catSel = target;
	catSel.style.ccsText = style_listSel + catSel.getAttribute("position");
	while(elementDiv.hasChildNodes()) {
		elementDiv.removeChild(elementDiv.firstChild);
	}
	elementDiv.appendChild(document.createTextNode("Loading..."));
	loadXML("a_milphPromo/xml/"+ target.getAttribute("id")+".xml", populateElements);
}

//-------- listRollOver -------------
function listRollOver(target) {
	target.style.cssText = style_listRoll + target.getAttribute("position");
}

//-------- listRollOut -------------
function listRollOut(target) {
	if (target != catSel & target != elemSel) {
		target.style.cssText = style_list + target.getAttribute("position");
	} else {
		target.style.cssText = style_listSel + target.getAttribute("position");
	}
}

//-------- populateElements -------------
function populateElements(xmldoc, url) {
if (xmldoc.readyState == 4) {
	elementObject = xmldoc.responseXML;
	elements = elementObject.getElementsByTagName("element");
	fillElements(0, elements.length);
}
}

function fillElements(start,end) {

	while(elementDiv.hasChildNodes()) {
		elementDiv.removeChild(elementDiv.firstChild);
	}
	
	for (var i=start; i < end; i++) {
		var e = elements[i];
		var value = e.getAttribute("name");
		var listDiv  = document.createElement("div");
		listDiv.setAttribute("id", e.getAttribute("id"));
		listDiv.setAttribute("onmouseover","listRollOver(this)");
		listDiv.setAttribute("onmouseout","listRollOut(this)");
		listDiv.setAttribute("onclick","elementClick(this)");
		try {
		//If we are in IE, need to attach events
        listDiv.attachEvent( "onmouseover", ie_dispatcher);
        listDiv.attachEvent( "onmouseout", ie_dispatcher);
        listDiv.attachEvent( "onclick", ie_dispatcher);
        } catch (ex) {}

		var listDivStyle = "position:absolute;left:0px;top:"+
			(rowHeight *(i-start)) +";height:"+rowHeight+";z-index:"+(10+i)+";"
			+"visibility: visible; display: block;";
		
		listDiv.setAttribute("position", listDivStyle);
		listDiv.style.cssText = style_list + listDivStyle;
		listDiv.setAttribute("elementNum",i);
		
		var imageDiv = document.createElement("div");
		imageDiv.style.cssText = "position:absolute;left:0px;top:2px;";
		
		var listImg = document.createElement("img");
		listImg.setAttribute("alt",value);
		listImg.setAttribute("src", config[0].getAttribute("thumbs")+"/"
		+e.getAttribute("category")+"/"+e.getAttribute("id"));
		listImg.setAttribute("valign","middle");
		
		try {
		//If we are in IE, need to fix the PNG
        listImg.attachEvent( "onload", ie_img_dispatcher);
        } catch (ex) {}
		
		imageDiv.appendChild(listImg);
		listDiv.appendChild(imageDiv);
		
		var textDiv = document.createElement("div");
		textDiv.style.cssText = "position:absolute;left:33px;top:7px;" +
								"width:300px;overflow:hidden";

		textDiv.appendChild(document.createTextNode(value));
		listDiv.appendChild(textDiv);
		elementDiv.appendChild(listDiv);
	}
}

//-------- elementClick -------------
function elementClick(target) {
	if (elemSel != null) {
		elemSel.style.cssText = style_list + elemSel.getAttribute("position");
		
	}
	elemSel = target;
	elemSel.style.ccsText = style_listSel + elemSel.getAttribute("position");
	while(detailDiv.hasChildNodes()) {
		detailDiv.removeChild(detailDiv.firstChild);
	}
	detailDiv.appendChild(document.createTextNode("Loading..."));
	populateDetail();
}

//-------- populateDetail -------------
function populateDetail() {
	while(detailDiv.hasChildNodes()) {
		detailDiv.removeChild(detailDiv.firstChild);
	}
	
		var e = elements[Number(elemSel.getAttribute("elementNum"))];
		var value = e.getAttribute("name");
		var listDiv  = document.createElement("div");
		listDiv.setAttribute("id", e.getAttribute("id"));

		var listDivStyle = "position:absolute;left:0px;top:"+
			"5px;width:100%;height:220;z-index:300;"
			+"visibility: visible; display: block;text-align:center;";
		
		listDiv.setAttribute("position", listDivStyle);
		listDiv.style.cssText = style_list + listDivStyle;
		listDiv.style.align = "center";
		
		var imageDiv = document.createElement("div");
		imageDiv.style.cssText = "position:absolute;left:5px;top:5px;" +
								"height:200px;overflow:hidden;width:100%;align:center;";
		
		var listImg = document.createElement("img");
		listImg.setAttribute("alt",value);
		listImg.setAttribute("src", config[0].getAttribute("images")+"/"
		+e.getAttribute("category")+"/"+e.getAttribute("id"));
		
		try {
		//If we are in IE, need to fix the PNG
        listImg.attachEvent( "onload", ie_img_dispatcher);
        } catch (ex) {}
		
		imageDiv.appendChild(listImg);
		listDiv.appendChild(imageDiv);
		
		var textDiv = document.createElement("div");
		textDiv.style.cssText = "position:absolute;left:5px;bottom:1px;" +
								"width:100%;overflow:hidden;text-align:center;";

		textDiv.appendChild(document.createTextNode(value));
		listDiv.appendChild(textDiv);
		detailDiv.appendChild(listDiv);
	
}

//-------- loadXML -------------
function loadXML(url, handler) {
	var http = getHTTPObject();
	if (http!= null) {
	http.open("GET", url, true);
	http.onreadystatechange = function() { handler(http, url); }
	http.send(null);
	}
}

function getHTTPObject() {
   try {
      if (window.XMLHttpRequest) {
         var req = new XMLHttpRequest();
         
         // some older versions of Moz did not support the readyState property
         // and the onreadystate event so we patch it!
         if (req.readyState == null) {
            req.readyState = 1;
            req.addEventListener("load", function () {
               req.readyState = 4;
               if (typeof req.onreadystatechange == "function")
                  req.onreadystatechange();
            }, false);
         }
         
         return req;
      }
      if (window.ActiveXObject) {
      
      return new ActiveXObject("MSXML2.XMLHTTP.3.0");
         //return new ActiveXObject(getControlPrefix() + ".XmlHttp");
      }
   }
   catch (ex) {}
   // fell through
   //throw new Error("Your browser does not support XmlHttp objects. "+ex);
   
   categoryDiv.appendChild(document.createTextNode("Your browser is not supported by the One Mile Up image viewer."));
   detailDiv.appendChild(document.createTextNode("Recommended Browsers:"));
   detailDiv.appendChild(document.createElement("br"));
   detailDiv.appendChild(document.createElement("br"));
   detailDiv.appendChild(document.createTextNode("Mac: Safari 1.2+, Mozilla 1.4+, Firefox 0.8+, Netscape 7.1+"));
   detailDiv.appendChild(document.createElement("br"));
   detailDiv.appendChild(document.createElement("br"));
   detailDiv.appendChild(document.createTextNode("Win: IE 5.5+, Mozilla 1.4+, Firefox (0.8+), Netscape 7.1+"));
   detailDiv.appendChild(document.createElement("br"));
   detailDiv.appendChild(document.createElement("br"));
   detailDiv.appendChild(document.createTextNode("Linux: Mozilla 1.4+, Firefox 0.8+, Netscape 7.1+"));


};

//-------- fixPNG -------------
function fixPNG(myImage) // correctly handle PNG transparency in Win IE 5.5 or higher.
   {                     // http://homepage.ntlworld.com/bobosola.
    if (window.ie55up)
         {
         var imgID = (myImage.id) ? "id='" + myImage.id + "' " : ""
         var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : ""
         var imgTitle = (myImage.title) ? "title='" + myImage.title + "' " : "title='" + myImage.alt + "' "
         var imgStyle = "display:inline-block;" + myImage.style.cssText 
         var strNewHTML = "<span " + imgID + imgClass + imgTitle
         strNewHTML += " style=\"" + "width:" + myImage.width + "px; height:" + myImage.height + "px;" + imgStyle + ";"
         strNewHTML += "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
         strNewHTML += "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>" 
         myImage.outerHTML = strNewHTML
         }
   }
   
function ie_img_dispatcher() {
try {
	if (event.srcElement.tagName == "IMG") {
		fixPNG(event.srcElement);
	} 
	} catch (err) { 
	//cannot processThePNG, gracefully do nothing
	}
}

//-------- applyStyle -------------
function applyStyle(oldStyle, newStyle) {
	var i;
	var oldPairs = oldStyle.split(';');
	//var newPairs = newStyle.split(';');
	var returnStyle = "";
	for (i = 0; i < oldPairs.length-1; i++) {
		datos = oldPairs[i].split(':');
		var thisProp = datos[0];
		//debug("oldPair " + i + " ..... " + thisProp);
		if(newStyle.indexOf(thisProp.trim()) != -1) {
			datos[1] = getStyleValue(newStyle, thisProp);
			//debug("Duplicate Property: "+thisProp);
		}
		returnStyle += datos[0] + ":" + datos[1] + ";";
	}
	
	var newPairs = newStyle.split(';');
	for (i = 0; i < newPairs.length-1; i++) {
		data = newPairs[i].split(':');
		var thisProp = data[0];
		if(oldStyle.indexOf(thisProp.trim()) == -1) {
			returnStyle += data[0] + ":" + data[1] + ";";
		}
	}
	
		//debug ("OLDSTYLE: "+ oldStyle + "    ......NEWSTYLE:"+newStyle+
		//		"               ........ReturnValue:"+returnStyle);
	
	return returnStyle;
}

function getStyleValue(styleStr, styleProp) {
	var i;
	stylePairs = styleStr.split(';');
	for (i=0; i < stylePairs.length; i++) {
		data = stylePairs[i].split(':');
		var thisProp = data[0];
		var thisValue = data[1];
		if (thisProp.indexOf(styleProp.trim()) != -1) {
			var styleValue = thisValue;
			break;
		}
	}
	return styleValue;
}

function trimString (str) {
  str = this != window? this : str;
  return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

String.prototype.trim = trimString;


//-------- toggleLayer -------------
function toggleLayer(whichLayer)
{
        if (document.getElementById)
        {
                // this is the way the standards work
                var style2 = document.getElementById(whichLayer).style;
                style2.display = style2.display? "":"block";
        }
        else if (document.all)
        {
                // this is the way old msie versions work
                var style2 = document.all[whichLayer].style;
                style2.display = style2.display? "":"block";
        }
        else if (document.layers)
        {
                // this is the way nn4 works
                var style2 = document.layers[whichLayer].style;
                style2.display = style2.display? "":"block";
        }
}


//-------- debug -------------
function debug(msg) {
    // If we haven't already created a box within which to display
    // our debugging messages, then do so now.  Note that to avoid
    // using another global variable, we store the box node as a property
    // of this function.
    if (!debug.box) {
        // Create a new <div> element
        debug.box = document.createElement("div");
        // Specify what it looks like using CSS style attributes
        debug.box.style.cssText= "background-color: yellow;position:absolute;bottom:0px; " +
                               ";height:250;overflow:auto;font-family: monospace; " +
                               "border: solid black 3px; " +
                               "padding: 10px;font-size:10px;";
        
        // And append our new <div> element to the end of the document
        document.body.appendChild(debug.box);

        // Now add a title to our <div>.  Note that the innerHTML property is
        // used to parse a fragment of HTML and insert it into the document.
        // innerHTML is not part of the W3C DOM standard, but it is supported
        // by Netscape 6 and Internet Explorer 4 and later.  We can avoid 
        // the use of innerHTML by explicitly creating the <h1> element,
        // setting its style attribute, adding a Text node to it, and 
        // inserting it into the document, but this is a nice shortcut
        debug.box.innerHTML =
            "<h1 style='text-align:center'>Debugging Output</h1>";
    }

    // When we get here, debug.box refers to a <div> element into which
    // we can insert our debugging message.
    // First, create a <p> node to hold the message
    var p = document.createElement("p");
    // Now create a text node containing the message, and add it to the <p>
    p.appendChild(document.createTextNode(msg));
    // And append the <p> node to the <div> that holds the debugging output
    debug.box.appendChild(p);
}