// JavaScript Document



function dataLoader() {
	
	//xmlObj = CreateXmlHttp();
	apiPath = "madison_projects.aspx";
	projects = [];
	slideshows = [];
	searchProjectsArray=[];
	featuredProject = 0;
	
	
	return {
		
		getXML: function() {
			

			$.get(apiPath+'?clearcache=true',this.buildLoader);
			/*if (xmlObj) {
				
				//xmlObj.onreadystatechange = checkDataStatus(xmlObj);
				
				xmlObj.onreadystatechange = function () {
					if (xmlObj.readyState == 4) {
						if (xmlObj.status == 200) {
							alert(constructor);
							constructor.dataHolder.buildLoader(xmlObj);		
						}
					}
				}

			} else {
				xmlObj = CreateXmlHttp();
			}
			
			xmlObj.open("GET",apiPath,true);
			xmlObj.send(null); */

		},
	
		buildLoader: function(xmlObj) {
	
				
				//loop through the XML, building the project thumbnail links
						//var projectXML = xmlObj.responseXML;
						
						//get the projects node
						var projectNodes = xmlObj.getElementsByTagName("projects")[0].childNodes;
						
						//loop through
						for (i=0;i<projectNodes.length;i++) {
							
							//check for the nodeType
							var projectNode = projectNodes[i];
							
							if (projectNode.nodeType==1) {
							
								//increment the number of images for the thumbnail slider
								//constructor.slider.imageNum++;
								
								var projectArray = [];
								//get props of this proj node
								projectArray["id"] = projectNode.getElementsByTagName("id")[0].firstChild.nodeValue;
								projectArray["name"] = projectNode.getElementsByTagName("name")[0].firstChild.nodeValue;
								projectArray["title"] = projectNode.getElementsByTagName("title")[0].firstChild.nodeValue;
								projectArray["description"] = projectNode.getElementsByTagName("description")[0].firstChild.nodeValue;
								projectArray["thumbnail"] = projectNode.getElementsByTagName("thumbnail")[0].firstChild.nodeValue;
								projectArray["featured"] = projectNode.getElementsByTagName("featuredProject")[0].firstChild.nodeValue;
								
								//create object to push to project array
								var projObj = {id:projectArray["id"], name:projectArray["name"],title:projectArray["title"]};
								searchProjectsArray.push(projObj);
								
								//add a thumbnail image to the project browser
								var thumbnaillink = document.createElement("a");
								thumbnaillink.setAttribute("id",projectArray["id"]);
								//thumbnaillink.setAttribute("href","#");
								//thumbnaillink.setAttribute("class","browserTnail");
								$(thumbnaillink).css("background-image","url(images/tnailloading.gif)");
								thumbnaillink.setAttribute("title",projectArray["name"]+": "+projectArray["title"]);
								$("#imgStrip").append(thumbnaillink);


								var img = new Image(); 
								img.setAttribute("id",projectArray["id"]);
								


										$(img).load(function () { 
												$(this).css('border','0'); // since .hide() failed in safari 
												$(this).addClass("browserTnail");
												//call the js to set up the rollover on the main page
												if (!window.rollOver) {
													window.rollOver = showRollOver();
												}
												$(this).click(function() {
													dataHolder.unloadProject($(this).attr("id"));									 
												});
												var whichLink = $("a#"+$(this).attr("id"));
												whichLink.css("background-image","none");
												whichLink.append($(this)); 
												$(this).fadeIn(); 
										}).error(function () { 
												//$(curr).remove(); 
										}).attr('src', projectArray["thumbnail"]);

	
								//push the project into the project array
								projects["project"+projectArray["id"]] =projectArray;

								
								//get the slideshow node
								var slideshowImages = projectNode.getElementsByTagName("slideshow")[0].childNodes;
								//loop
								var imageholder = [];
								for (j=0;j<slideshowImages.length;j++) {
									var imageNode = slideshowImages[j];
									if (imageNode.nodeType == 1) {
										var imageArray = [];
										imageArray["imgPath"] = imageNode.getElementsByTagName("src")[0].firstChild.nodeValue;
										//before src may be an empty string
										if (imageNode.getElementsByTagName("beforesrc")[0].firstChild) {
											imageArray["beforeImgPath"] = imageNode.getElementsByTagName("beforesrc")[0].firstChild.nodeValue;
										} else {
											imageArray["beforeImgPath"] = '';
										}
										//caption may be an empty string
										if (imageNode.getElementsByTagName("caption")[0].firstChild) {
											imageArray["caption"] = imageNode.getElementsByTagName("caption")[0].firstChild.nodeValue;
										} else {
											imageArray["caption"] = '';
										}
										imageholder.push(imageArray);
									}
								}
								
								slideshows["slideshow"+projectArray["id"]] = imageholder;
								
								//if you came to this page from a project search, you'll have the URL parameter appended
								if ($.getURLParam("p")==null) {
									if (projectArray["featured"] == "true") {
										//store the featured project var.  The FLASH will load the project in when it's done loading
										featuredProject = projectArray["id"];
										//dataHolder.loadProject(projectArray["id"]);
									}
								} else {
									featuredProject = ($.getURLParam("p"));
								}

							
							}
	
						}		
						
											
							
							//end for loop
							$("#projectSearchBox").autocomplete(searchProjectsArray,{minChars:2, scrollHeight:500, multiple:false, matchContains: true, autoFill: false, selectFirst: false,
							formatItem: function(row, i, max) {return row["name"]+": "+row["title"]}});
							$('input#projectSearchBox').result(function(event, data, formatted) {$("#ps_btn").click(function() {dataHolder.unloadProject(data.id);});});
							//enable the search textbox
							$("input#projectSearchBox").attr("disabled",this.value == 'no');
							dataHolder.loadProject(window.featuredProject);
							
			},
	
			//called FROM the flash when a project is done unloading. This will load the new stuff in
			loadProject:function(whichProj) {
					var isIE = navigator.appName.indexOf("Microsoft") != -1;
					
					if (isIE) {
						 var flashMovie = window['slideshowflash'];
					} else {
						var flashMovie = document['slideshowflash'];
					}	
					
					
					//if (!flashMovie) {
					//	setTimeout(this.loadProject(whichProj),1000);
				//		return;
				//	}
					
					//get all the children of the tnail slider and set style to have NO border
					//$("#imgStrip").children().addClass("tnailnotselected");
					var $kids = $("#imgStrip").children();
					//$kids.addClass("tnailnotselected");
					var thisSlideshow = slideshows["slideshow"+whichProj];
					//write out new title SWF
					var t = new SWFObject("swf/title.swf", "projecttitles", "414", "56", "7", "#ffffff");
					t.addVariable("title", projects["project"+whichProj]["name"]);
					t.addVariable("subtitle", projects["project"+whichProj]["title"]);
					t.addParam("wmode", "transparent");
					t.write("subhead_ourwork");
					//write out description in page
					document.getElementById('body_sub').innerHTML = projects["project"+whichProj]["description"]
					//need to loop through array and send each image to Flash to
					//avoid sending multidimensional array
					for (k=0; k<thisSlideshow.length;k++) {
						flashMovie.addImage(thisSlideshow[k]["imgPath"],thisSlideshow[k]["beforeImgPath"],thisSlideshow[k]["caption"]);
					}
					//when you're done looping, tell the Flash to load up the images
					flashMovie.loadImages();
			},
			
			//called when you click a thumbnail. This gets the Flash to completely UNLOAD the current slideshow.  It will then call the 
			//load project to load it in new
			unloadProject:function(whichProj) {
							
					var isIE = navigator.appName.indexOf("Microsoft") != -1;
					if (isIE) {
						 var flashMovie = window['slideshowflash'];
					} else {
						var flashMovie = document['slideshowflash'];
					}				
					flashMovie.initShow(whichProj);
			},
			
			loadFirstProject:function() {
				if ($.getURLParam("p")!=null) {
					dataHolder.loadProject($.getURLParam("p"))
				} else {
					dataHolder.loadProject(window.featuredProject);
				}
			}

}};


function CreateXmlHttp()

{
    //Creating object of XMLHTTP in IE
    try
    {
        var XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
        try
        {
            var XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(e)
        {
           var  XmlHttp = null;
        }
    }
    //Creating object of XMLHTTP in Mozilla and Safari
    if(!XmlHttp && typeof XMLHttpRequest != "undefined")
    {
       var  XmlHttp = new XMLHttpRequest();
    }
		
		return XmlHttp;
		
}