/**
 * @author giuseppe
 */
window.onload = function()
{
	page.init();
	loadFlash();
}
page = new Object();
page._x_sizeA = 1280;
page._y_sizeA = 840;
page._x_sizeB = 1024;
page._y_sizeB = 659;
page.window_size = page._x_sizeB;
page.current_clicked = null;
page.current_selected = null;
page.first_time = true;
page.first_load = true;
page.default_page = 'Home';
page.image__template = {
	filename: '',
	name: '',
	i: new Image()
};
page.images = new Array();
page.current_image = 'b';
page.current_image_index = 0;
page.is_regenerating = 'true';
page.image_loading_timeout = null;
page.image_loading_timeout_time = 9000;
page.current_clicked_type = null;
//page.xml_path = 'http://webserver:2228';
page.xml_path = 'http://www.productoftheyear.in';

page.init = function()
{
	NETJOHNHENRY.Ajax.load({
		url: '/poy.partials.aspx?output_file=sitemap.xml&xsl_path=' + page.xml_path + '/xslt/sitemap.xsl&is_regenerating=' + page.is_regenerating,
		onloadfunction: page.sitemapLoaded
	});
	NETJOHNHENRY.Ajax.start_navigating_by_ajax({
		file_extension: '.xml',
		urlconstructfunction: page.urlconstructfunction,
		onloadfunction: page.xmlLoaded,
		onchangefunction: page.findOwnMenu,
		default_page: page.default_page
	});
}

page.urlconstructfunction = function(pagename)
{
	//Used by NETJOHNHENRY.Ajax.start_navigating_by_ajax to construct the url where to find the partials generator.	
	// the path could be passed as full path #the_residence/guestrooms
	// or #guestrooms, the following lines split the pagename before creating the final url.
	
	var path = pagename.split('/');
	pagename = path[path.length - 1];

	return '/poy.partials.aspx?is_regenerating=' + page.is_regenerating + '&output_file=' + escape(pagename) + '.xml&xsl_path=' + page.xml_path + '/xslt/page.xsl';
}

//This function is called by NETJOHNHENRY.Ajax.start_navigating_by_ajax once a the content of a new page is loaded.
page.xmlLoaded = function(xmlobj)
{
	var xmlobj = arguments[0].responseXML;
	var contentPattern = '//page/contents';
	var contentIterator = NETJOHNHENRY.Document.evaluate(contentPattern, xmlobj, null, 0, null);
	var content = contentIterator.iterateNext();
	
	var c = content.textContent;
    
    document.getElementById('content').innerHTML = c;					
	
	var metatitle = '//page/extras/metatitle';
	var titleIterator = NETJOHNHENRY.Document.evaluate(metatitle, xmlobj, null, 0, null);
	
	if (titleIterator!=null)
	{
		var mTitle = titleIterator.iterateNext();
		
		document.getElementById('title').content = mTitle.textContent;
	}
	
	var metakeywords = '//page/extras/metakeywords';
	var keywordsIterator = NETJOHNHENRY.Document.evaluate(metakeywords, xmlobj, null, 0, null);
	
	if (keywordsIterator!=null)
	{
		var mKeywords = keywordsIterator.iterateNext();
		document.getElementById('keywords').content = mKeywords.textContent;
	}
	
	var metadescription = '//page/extras/metadescription';
	var descriptionIterator = NETJOHNHENRY.Document.evaluate(metadescription, xmlobj, null, 0, null);
	
	if (descriptionIterator!=null)
	{
		var mDescription = descriptionIterator.iterateNext();
		document.getElementById('description').content = mDescription.textContent;
	}
	
	var imagePattern = '//page/extras/images/image';
	var imagesIterator = NETJOHNHENRY.Document.evaluate(imagePattern, xmlobj, null, 0, null);
	var images;
	page.images = new Array();
	while (images = imagesIterator.iterateNext()) 
	{
		page.images.push({
			filename: images.attributes['filename'].value//,
			//caption: images.attributes['caption'].value			
		});
	}
	if (page.images.length > 0) 
	{
		if (page.image_loading_timeout) 
		{
			clearTimeout(page.image_loading_timeout)
		};
		page.current_image_index = -1;
		page.loadImages();
		
	}
	
	var location_array = page.getLocationArray();
	//load secondary nav when site first loads
	if (page.first_load = true)
	{
		page.nav_1a__click(location_array[0]);
		page.first_load = false;
	}
	
	if (location.href.indexOf("#") < 0)
	{
		page.nav_click_linkboxes("Home",1);
	}
}

page.findOwnMenu = function()
{
	/*	try{*/
	if (page.current_clicked_type == '1a') 
	{
		return;
	}
	var location_array = page.getLocationArray();
	try 
	{
		if (page.current_selected !=null && page.current_selected !='undefined')
		{
			page.current_selected.className = 'off';
		}
	} 
	catch (e) 
	{
	}
	page.current_selected = document.getElementById('nav_1a.li.node_of::' + location_array[0] + '::') || document.getElementById('nav_1b.li.node_of::' + location_array[0] + '::');
	try 
	{
		if (page.current_selected !=null && page.current_selected !='undefined')
		{
			page.current_selected.className = 'on';
		}	
	} 
	catch (e) 
	{
	};
	
	
	/*	}catch(e){
	 try {console.log(e);}catch(e){}
	 }
	 */
}

page.sitemapLoaded = function(xmlobj)
{
	
	//Sitemap loaded, split it into top navigation an bottom one	
	xmlobj = arguments[0].responseXML;
	var contentPattern = '//sitemap/branch';
	var contentIterator = NETJOHNHENRY.Document.evaluate(contentPattern, xmlobj, null, 0, null);
	var branch;
	
	var main_menu = document.getElementById('topnav');
	
	
	while (branch = contentIterator.iterateNext()) 
	{
		//top and bottom navigation a and b
		switch (branch.attributes['type'].value)
		{
			case 'a':
				//alert(branch.textContent);
				document.getElementById('topnav').innerHTML = branch.textContent;
				break;
			case 'b':
				document.getElementById('bottomnav').innerHTML = branch.textContent;
				break;
			case 'c':
				//alert(branch.textContent);
				document.getElementById('linkboxes').innerHTML = branch;
				break;	
			
		}
	}
	
	
	
	var myFx = new Fx.Style(main_menu.id, 'opacity', {
		duration: 80
	}).start(0, 0.8); //display a transition from transparent to opaque.

}

page.getLocationArray = function()
{
	//we don't own control over the address bar so let it handle gracefully in a try catch	
	try 
	{
		if (location.href.indexOf("#") > 0)
		{
			return location.href.split('#')[1].split('/');
		} else {
			return page.default_page.split('/');
		}
	} 
	catch (e) 
	{
		return page.default_page.split('/');
	}
}

//loading images 
page.loadImages = function()
{
	var i = new Image();
	var i_name;
	page.current_image_index = (++page.current_image_index >= page.images.length) ? 0 : page.current_image_index;
	i_name = page.images[page.current_image_index];
	i.src = '/images/' + page.window_size + '/' + i_name.filename;

	
	i.onload = function()
	{
		var old_img;
		var img_type = page.current_image == 'a' ? 'b' : 'a';
		var img_id = 'image_' + img_type;
		var img;
		if(!(img = document.getElementById(img_id))){
			var images = document.getElementById('images');
			var image_element = new Element('img');
			image_element.id = img_id;
			images.appendChild(image_element);		
			img = document.getElementById(img_id);	
		};
		var myFx = new Fx.Style(img.id, 'opacity').set(0); //will make it immediately transparent				
		img.src = i.src;
		img.style.zIndex = 3;
		if (old_img = document.getElementById('image_' + page.current_image)) 
		{
			old_img.style.zIndex = 2;
		}
		var myFx = new Fx.Style(img.id, 'opacity', {
			duration: 2000
		}).start(0, 1); //display a transition from transparent to opaque.	    
		
		page.current_image = img_type;
		
		if (page.images.length > 1) 
		{
			page.image_loading_timeout = setTimeout(page.loadImages, page.image_loading_timeout_time);
		}
		
	}
}

page.navigation_2__apply_mouseevents = function()
{
	var n = document.getElementById('footer');
	var status = 0; // 1 | 0 = open | close
	var close_timeout;
	n.onmouseover = function()
	{
		clearTimeout(close_timeout);
		status = 1;
	}
	n.onmouseout = function()
	{
		if (n.style.display == 'none') 
		{
			return;
		}
		var closeMenu = function()
		{
			console.log("out " + status);
			if (status == 0) 
			{
				page.closeMenu();
			}
		}
		status = 0;
		clearTimeout(close_timeout);
		close_timeout = setTimeout(closeMenu, 200);
	}
}

page.testelement = function()
{
   var chkele = document.getElementById("scroller_1");
   //alert(chkele);
   if (chkele)
    {
        populate();
    }    
    return chkele;
}

page.nav_click_linkboxes = function(sender,level)
{
	//checks for linkboxes and then displays
	var lb = document.getElementById('linkboxes');
	var trycount = 0;
	//alert(sender + "\n" + level);
	
	if (level!=2)
	{
	    if (document.getElementById('linkbox_top_' + sender))
	    {
    		
		    var lp = document.getElementById('linkbox_top_' + sender).innerHTML;
    		lp = lp.replace("id=\"scroller\"","id=\"scroller_1\"")
    		lp = lp.replace("id=\"scrollercontain\"","id=\"scrollercontain_1\"")
    		
    		lb.innerHTML = "<ul>" + lp + "</ul>";
	    } 
	    else
	    {
		    lb.innerHTML = "";	
	    }
	} else { 
	    //alert('linkbox_top_2ndlevel_' + sender);
	    if (document.getElementById('linkbox_top_2ndlevel_' + sender))
	    {
    		
		    var lp = document.getElementById('linkbox_top_2ndlevel_' + sender).innerHTML;
    		
		    lb.innerHTML = "<ul>" + lp + "</ul>";
	    } 
	    else
	    {
		    lb.innerHTML = "";	
	    }
	} 
	
	//alert(document.getElementById("scroller_1"));
	/*if (document.getElementById("scroller"))
    {
	    
	  var chk = page.testelement();
	   
      if (!chk)
      {
        //try the function every 0.5secs for 3.5secs.
        var myInterval = setInterval('page.testelement()', 500 );
        
        window.setTimeout('clearInterval(' + myInterval + ')',50000)
      }  
	    
	   
    } */   
}

page.nav_1a__click = function(sender)
{
	//hides any submenus already displayed 
	var tc = document.getElementById('topnav').childNodes;
		
    for(i=0;i<tc.length;i++)
    {
        
        //alert(tc[i].id.indexOf('nav_2a_'));
        if (tc[i].id.indexOf('nav_2a_') != -1)
        {
            tc[i].style.display = 'none';
        }
    }
	//checks for id then displays
	if (document.getElementById('nav_2a_' + sender))
	{
	    var el = document.getElementById('nav_2a_' + sender);
	    
	    el.style.display = 'block';
	    el.style.clear = 'left';	
    }
	
	page.nav_click_linkboxes(sender,1);

}

/*page.getLocationArray = function()
{
	//we don't own control over the address bar so let it handle gracefully in a try catch	
	try 
	{
		return location.href.split('#')[1].split('/');
	} 
	catch (e) 
	{
		return page.default_page.split('/');
	}
}*/

//loading images 
page.loadImages = function()
{
	var i = new Image();
	var i_name;
	page.current_image_index = (++page.current_image_index >= page.images.length) ? 0 : page.current_image_index;
	i_name = page.images[page.current_image_index];
	i.src = '/images/' + page.window_size + '/' + i_name.filename;

	
	i.onload = function()
	{
		var old_img;
		var img_type = page.current_image == 'a' ? 'b' : 'a';
		var img_id = 'image_' + img_type;
		var img;
		if(!(img = document.getElementById(img_id))){
			var images = document.getElementById('images');
			var image_element = new Element('img');
			image_element.id = img_id;
			images.appendChild(image_element);		
			img = document.getElementById(img_id);	
		};
		var myFx = new Fx.Style(img.id, 'opacity').set(0); //will make it immediately transparent				
		img.src = i.src;
		img.style.zIndex = 3;
		if (old_img = document.getElementById('image_' + page.current_image)) 
		{
			old_img.style.zIndex = 2;
		}
		var myFx = new Fx.Style(img.id, 'opacity', {
			duration: 2000
		}).start(0, 1); //display a transition from transparent to opaque.	    
		
		page.current_image = img_type;
		
		if (page.images.length > 1) 
		{
			page.image_loading_timeout = setTimeout(page.loadImages, page.image_loading_timeout_time);
		}
		
	}
}

page.navigation_2__apply_mouseevents = function()
{
	var n = document.getElementById('footer');
	var status = 0; // 1 | 0 = open | close
	var close_timeout;
	n.onmouseover = function()
	{
		clearTimeout(close_timeout);
		status = 1;
	}
	n.onmouseout = function()
	{
		if (n.style.display == 'none') 
		{
			return;
		}
		var closeMenu = function()
		{
			console.log("out " + status);
			if (status == 0) 
			{
				page.closeMenu();
			}
		}
		status = 0;
		clearTimeout(close_timeout);
		close_timeout = setTimeout(closeMenu, 200);
	}
                
}

//fade text in on spalsh page.
/*hexri=222; // Initial color value.
hexgi=90;
hexbi=95;

hexre=140;
hexge=198;
hexbe=62;
speed=50;
hexrDelta=(hexre-hexri)/speed;
hexgDelta=(hexge-hexgi)/speed;
hexbDelta=(hexbe-hexbi)/speed;
hexr=hexri+hexrDelta;
hexg=hexgi+hexgDelta;
hexb=hexbi+hexbDelta;
blnBack=false;

fadetext = function()
{ 
	if(speed>0) { //If color is not black yet
		hexr+=hexrDelta;
		hexg+=hexgDelta;
		hexb+=hexbDelta;
		document.getElementById("rhs").getElementsByTagName("a")[0].style.color="rgb("+parseInt(hexr)+","+parseInt(hexg)+","+parseInt(hexb)+")";
		setTimeout("fadetext()",20); 
		speed--;
	}else{
	
	}
}*/


page.loadFlash = function(flashfile,element)
{
	var myFlash = new FlashTag();
	myFlash.version = 8; // or whatever you need - default is 7
	myFlash.src = '/flash/' + flashfile; // url of your SWF file
	myFlash.width = 643;
	myFlash.height = 409;
	myFlash.writeToElement(element); // writes the code into the element with this id
}
