var selected;
var selected_ref = 0;
var selected_id = "";
//	our favourite counters
var i = 0;
var j = 0;
//	the xml to populae the gallery
var xmlDoc;
//	and the bits-n-bos init
var hotspots;
var titles;
var icons;
var descs;
var images;
var jsimages;
var ids;
//	we'll put em in here
var kimages = new Array();
// our new friend
var xmlHttp;
var xmlDoc;
var mylang;
var gallery;
// what is says on the tin
var page;	

function init(xml,lang)	
{

	if(lang)
		mylang = lang;
	else
		mylang = "en";
		
	preloadImages();
	
	page = document.getElementsByTagName('body')[0].attributes.getNamedItem('id').value;
	
	switch(page)
	{
	case 'landing':
	  //
	  break;    
	case 'aseries_page':
	 $('aseries').getElementsByTagName('img')[0].src = "images/nav/nav_a_"+mylang+"_hv.gif";	  
	  break;
	case 'kseries_page':
	  $('kseries').getElementsByTagName('img')[0].src = "images/nav/nav_k_"+mylang+"_hv.gif";	
	  break;    
	case 'camileo_page':
	  $('camileo').getElementsByTagName('img')[0].src = "images/nav/nav_camileo_"+mylang+"_hv.gif";
	  break;
	case 'accessories_page':
	  $('accessories').getElementsByTagName('img')[0].src = "images/nav/nav_accessories_"+mylang+"_hv.gif";
	  break;    
	case 'reviews_page':
	  $('reviews').getElementsByTagName('img')[0].src = "images/nav/nav_reviews_"+mylang+"_hv.gif";
	  break;
	default:
	  //
	}

	prepareImageSwap(document.body);

	if(xml && xml!="null")
	{	
		gallery = xml;
				
		var links = $('fe')
		for(var j=0;j<links.length;j++)	
			addEventHandlers(links[j].id, j);	

		//  XMLHttpRequest is the best way to get the XML......
		var xmlHttp = createXmlHttpRequestObject(gallery);
	}
	
}

function addEventHandlers(id,ref) 
{

	var el = document.getElementById(id);
	el.onmouseover = function () 
	{  
		this.id = id;
		$(this.id).style.backgroundPosition = '0px -30px';
	}
	el.onmouseout = function () 
	{  
		this.id = id;
		if(selected_id != this.id)
			$(this.id).style.backgroundPosition = '0px 0px';
	}
	el.onclick = function () 
	{  
		this.id = id;
		switchGallery(kimages[ref])
	}

}
	
function switchGallery(kImage)
{
	selected_ref = kImage.ref;
	selected_id = kImage.id;

	if(selected_ref != 0)
		$('galleryfocus').style.visibility = 'visible';
	else
		$('galleryfocus').style.visibility = 'hidden';
	
	$(kImage.id).style.backgroundPosition = '0px -30px';
	$('selectedicon').style.background = "white url(" + kImage.icon + ") 0px -30px";

	if(selected)	{
		$(selected).style.backgroundPosition = '0px 0px';
	}

	$('galleryitem').style.background = "white url(" + kImage.src + ")";
	$('selecteddescription').innerHTML = "<p>" + kImage.desc + "</p>";
	$('selecteditem').innerHTML = "<h3><img src=\"" + kImage.title + "\" \></h3>";
	
	selected = kImage.id;
}

/*	direction nav	*/
function nextFeature()	
{
	if(selected_ref<10)	
		selected_ref++;
	else
		selected_ref = 0;
	switchGallery(kimages[selected_ref]);
}

function previousFeature()	
{
	if(selected_ref>0)	
		selected_ref--;
	else
		selected_ref = 10;		
	switchGallery(kimages[selected_ref]);
}


function loaded()
{

	var allLanguages = xmlDoc.getElementsByTagName('allspots');
		
		//alert("lang is  :" + allLanguages[i].attributes.getNamedItem("lang").value);
		
		for(i=0;i<allLanguages.length;i++)
		{	
			if(allLanguages[i].attributes.getNamedItem("lang").value == mylang)
			{
			
				hotspots = allLanguages[i].getElementsByTagName('hotspot');
					
					//alert(hotspots.length + " hotspots found");
					
				for (i=0; i<hotspots.length; i++)
				{

					kimages[i] = new Image();

					kimages[i].src = hotspots[i].getElementsByTagName('jsimage')[0].firstChild.nodeValue;
					kimages[i].title = hotspots[i].getElementsByTagName('titleimage')[0].firstChild.nodeValue;
					kimages[i].icon = hotspots[i].getElementsByTagName('jsicon')[0].firstChild.nodeValue;
					kimages[i].desc = hotspots[i].getElementsByTagName('text')[0].firstChild.nodeValue;
					//	get the id from the attribute
					kimages[i].id = hotspots[i].attributes.getNamedItem("name").value;		
					
					
					kimages[i].ref = i;
					;
						
					var el = $(hotspots[i].attributes.getNamedItem("name").value);
					//alert(hotspots[i].attributes.getNamedItem("name").value);
					
					el.attributes.getNamedItem("title").value = hotspots[i].getElementsByTagName('title')[0].firstChild.nodeValue;
					
					//alert(hotspots[i].getElementsByTagName('title')[0].firstChild.nodeValue);
					
				}

			}
				
		}
	
	$('galleryitem').style.background = "white url(" + kimages[0].src + ")";
	$('selectedicon').style.background = "white url(" + kimages[0].icon + ") 0px -30px";
	$('selecteddescription').innerHTML = "<p>" + kimages[0].desc + "</p>";
	$(kimages[0].id).style.backgroundPosition = '0px -30px';
	selected = kimages[0].id;
	
}

// creates an XMLHttpRequest instance
function createXmlHttpRequestObject() 
{
  
  // this should work for all browsers except IE6 and older
  try
  {
    // try to create XMLHttpRequest object
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
  

    // assume IE6 or older
    var XmlHttpVersions = new Array('MSXML2.XMLHTTP.6.0',
                                    'MSXML2.XMLHTTP.5.0',
                                    'MSXML2.XMLHTTP.4.0',
                                    'MSXML2.XMLHTTP.3.0',
                                    'MSXML2.XMLHTTP',
                                    'Microsoft.XMLHTTP');
    // try every prog id until one works
    for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) 
    {
      try 
 
      { 
        // try to create XMLHttpRequest object
        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      } 
      catch (e) {}
    }
  }

  if (xmlHttp)
  {
    // try to connect to the server
    try
    {
	  xmlHttp.open("GET", gallery, true);
      xmlHttp.onreadystatechange = handleRequestStateChange;
      xmlHttp.send(null);
    }
    // display the error in case of failure
    catch (e)
    {
	
      manual_getXML();
    }
  }
  
  else	// try and get the xml another way.....
  {
	manual_getXML();
  }
}

function manual_getXML()
{
	//	this will not work for some safari versions
	var moz = (typeof document.implementation != 'undefined') && (typeof document.implementation.createDocument != 'undefined');
	var ie = (typeof window.ActiveXObject != 'undefined');

	if (moz) {
		xmlDoc = document.implementation.createDocument("", "", null);
		xmlDoc.load(gallery); 
		xmlDoc.onload = loaded;
	} else if (ie) {	// some people do use it
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); 
		xmlDoc.async="false";
		while(xmlDoc.readyState != 4) 
		{// do nothink	
		}; 
		// then....
		xmlDoc.load(gallery);
		loaded();
	}  
}

function handleRequestStateChange() 
{

  if (xmlHttp.readyState == 4)  
  {
    if (xmlHttp.status == 200) 
    {
      try
      {
        handleServerResponse();
      }
      catch(e)
      {
        manual_getXML();
      }
    } 
    else
    {
	  manual_getXML();
    }
  }
}


function handleServerResponse()
{
  var xmlResponse = xmlHttp.responseXML;
 
  //	catch potential errors
  if(!xmlResponse || !xmlResponse.documentElement)
	throw("Invalid XML structure:\n" + xmlHttp.responseText);

  xmlDoc = xmlResponse.documentElement;   
  loaded(xmlDoc);
   
}

function preloadImages()
{
	image1 = new Image();
	image1.src = "images/nav/nav_a_"+mylang+"_hv.gif";
	image2 = new Image();
	image2.src = "images/nav/nav_k_"+mylang+"_hv.gif";
	image3 = new Image();
	image3.src = "images/nav/nav_camileo_"+mylang+"_hv.gif";
	image4 = new Image();
	image4.src = "images/nav/nav_accessories_"+mylang+"_hv.gif";
	image5 = new Image();
	image5.src = "images/nav/nav_reviews_"+mylang+"_hv.gif";
}

//	our new favourite function
//	gets everything! This is wicked!
function $() {

	var elements = new Array();
	for (var i=0,len=arguments.length;i<len;i++) {
		var element = arguments[i];
		if (typeof element == 'string') {
			var matched = document.getElementById(element);
			if (matched) {
				elements.push(matched);
			} else {
				var allels = (document.all) ? document.all : document.getElementsByTagName('*');
				var regexp = new RegExp('(^| )'+element+'( |$)');
				for (var i=0,len=allels.length;i<len;i++) if (regexp.test(allels[i].className)) elements.push(allels[i]);
			}
			if (!elements.length) elements = document.getElementsByTagName(element);
			if (!elements.length) {
				elements = new Array();
				var allels = (document.all) ? document.all : document.getElementsByTagName('*');
				for (var i=0,len=allels.length;i<len;i++) if (allels[i].getAttribute(element)) elements.push(allels[i]);
			}
			if (!elements.length) {
				var allels = (document.all) ? document.all : document.getElementsByTagName('*');
				for (var i=0,len=allels.length;i<len;i++) if (allels[i].attributes) for (var j=0,lenn=allels[i].attributes.length;j<lenn;j++) if (allels[i].attributes[j].specified) if (allels[i].attributes[j].nodeValue == element) elements.push(allels[i]);
			}
		} else {
			elements.push(element);
		}
	}
	if (elements.length == 1) {
		return elements[0];
	} else {
		return elements;
	}
}


/* image rollovers  */
function prepareImageSwap(elem,mouseOver,mouseOutRestore,mouseDown,mouseUpRestore,mouseOut,mouseUp) { 
//Do not delete these comments. 
//Non-Obtrusive Image Swap Script V1.1 by Hesido.com 
//Attribution required on all accounts 



    if (typeof(elem) == 'string') elem = document.getElementById(elem); 
    if (elem == null) return; 
    var regg = /(.*)(_nm\.)([^\.]{3,4})$/ 
    var prel = new Array(), img, imgList, imgsrc, mtchd; 
    imgList = elem.getElementsByTagName('img'); 
    for (var i=0; img = imgList[i]; i++) { 
        if (!img.rolloverSet && img.src.match(regg)) { 
            mtchd = img.src.match(regg); 
            img.hoverSRC = mtchd[1]+'_hv.'+ mtchd[3]; 
            img.outSRC = img.src; 
            if (typeof(mouseOver) != 'undefined') { 
                img.hoverSRC = (mouseOver) ? mtchd[1]+'_hv.'+ mtchd[3] : false; 
                img.outSRC = (mouseOut) ? mtchd[1]+'_ou.'+ mtchd[3] : (mouseOver && mouseOutRestore) ? img.src : false; 
                img.mdownSRC = (mouseDown) ? mtchd[1]+'_md.' + mtchd[3] : false; 
                img.mupSRC = (mouseUp) ? mtchd[1]+'_mu.' + mtchd[3] : (mouseOver && mouseDown && mouseUpRestore) ? img.hoverSRC : (mouseDown && mouseUpRestore) ? img.src : false; 
                } 
            if (img.hoverSRC) {preLoadImg(img.hoverSRC); img.onmouseover = imgHoverSwap;} 
            if (img.outSRC) {preLoadImg(img.outSRC); img.onmouseout = imgOutSwap;} 
            if (img.mdownSRC) {preLoadImg(img.mdownSRC); img.onmousedown = imgMouseDownSwap;} 
            if (img.mupSRC) {preLoadImg(img.mupSRC); img.onmouseup = imgMouseUpSwap;} 
            img.rolloverSet = true; 
        } 
    } 
    function preLoadImg(imgSrc) { 
        prel[prel.length] = new Image(); prel[prel.length-1].src = imgSrc; 
    } 
} 

function imgHoverSwap() {this.src = this.hoverSRC;} 
function imgOutSwap() {this.src = this.outSRC;} 
function imgMouseDownSwap() {this.src = this.mdownSRC;} 
function imgMouseUpSwap() {this.src = this.mupSRC;}

