/***		prototypes		***/
Object.extend(String.prototype, {
  isNumber: function() {
	for (i = 0; i < this.length; i++)
		if("0123456789".indexOf(this.charAt(i))==-1) return false;
	return true;
  },
  isNumeric: function() {
	for (i = 0; i < this.length; i++)
		if("0123456789.".indexOf(this.charAt(i))==-1) return false;
	return true;
  }
});

/***		/ prototypes		***/
var debugmode = false;
var _showCityRegisterNumber = 12;
var regObjCountry = null;
var regObjCity = null;

var boxEvent = function(event){
	var id = Event.element(event).id;
	if(id != null){                                
		switch(id) {
			case "select_country":
				reset("city");
				reset("branch");
				reset("division");
				reset("country_description");
				setCityText($("select_country").options[$("select_country").selectedIndex].text);
        changeSize("select_city", 10);                                 
				loadData("cities", "country=" + $F(id));                                
				break;
			case "select_city":	
				reset("branch");
				reset("division");
        changeSize("select_branch", 10);
				loadData("branches", "country=" + $("select_country").value + "&city=" + $F(id));
				break;
			case "select_branch":
				reset("division");
				loadData("division", "id=" + $F(id));
				break;
			default:
				if(debugmode) throw("No proper id was found!");
		}                
		changeSize(id, 1);
	} else {
		if(debugmode)
			throw("id is null or current value is not a number!");
	}
}

var registerEventCity = function(event){
	reset("branch");
	reset("division");
    changeSize("select_city", 10);
	var Char = Event.element(event).firstChild.nodeValue;
	$("cityChar").value=Char;
	regObjCity.change(Char);
	$("select_city").selectedIndex = -1;
	if ($("select_city").options.length == 1) {
    	$("select_city").selectedIndex = 0;
        changeSize("select_city", 1);
         loadData("branches", "country=" + $("select_country").value + "&city=" + $("select_city").options[0].value);
	}
	Event.stop(event);
};

var registerEventCountry = function(event){
	$("country_description").hide();
	reset("city");
	reset("branch");
	reset("division");
	reset("country_description");
    changeSize("select_country", 10);
	var Char = Event.element(event).firstChild.nodeValue;
	$("countryChar").value=Char;
	regObjCountry.change(Char);
	$("select_country").selectedIndex = -1;
	if ($("select_country").options.length == 1) {
		$("select_country").selectedIndex = 0;
        changeSize("select_country", 1);
        loadData("cities", "country=" + $("select_country").options[0].value);
	}
		Event.stop(event);
};


function changeSize(elm, sizevalue) {  

   selectedelm = $(elm).selectedIndex; 
	var newSLC = document.createElement("select");
	newSLC.id = $(elm).id;
  newSLC.name = $(elm).name;
  
  if(sizevalue > 10) {
    newSLC.size = 10;
  } else {
    newSLC.size = sizevalue;
  }  
  
	newSLC.className = $(elm).classNames();		
	var optionArray =  new Array($(elm).childNodes.length);
    for (var i=0;i<optionArray.length;i++) {
      optionArray[i] = document.createElement("option");
      optionArray[i].setAttribute("value", $(elm).childNodes[i].getAttribute("value"));
      optionArray[i].appendChild(document.createTextNode( $(elm).childNodes[i].firstChild.nodeValue ));
      newSLC.appendChild(optionArray[i]);
    }		
    $(elm).parentNode.replaceChild(newSLC, $(elm) );
    
    if (selectedelm != -1){
    	$(elm).selectedIndex = selectedelm;
    }   
    
    if (elm.indexOf('country') > -1) {
      if (regObjCountry) regObjCountry.box = newSLC;
    } else if (elm.indexOf('city') > -1) {
      if (regObjCity) regObjCity.box = newSLC;
    }
    Event.observe(newSLC, 'change', boxEvent, false);
}


function loadData(type, query){
	var params = "type=" + type + ((query.length > 0)?"&" + query:"");
	
	var myAjax = new Ajax.Request(
		"xml.do", 
		{
			method: "post", parameters: params,
			onComplete: initResponseData,
			onFailure : function(resp, e) {
				if(debugmode) alert("onFailure: " + e);
				else showError();
			},
			onException : function(resp, e) {
				if(debugmode) alert("onException: " + e);
				else showError();
				Ajax.activeRequestCount--;
				Element.hide('systemWorking');
			}
		}
	);
}

Ajax.Responders.register({
	onCreate: function(){
		Element.show('systemWorking');
	},
	onComplete: function() {
		if(Ajax.activeRequestCount == 0){
		Element.hide('systemWorking');  
		}
	}
});

function initResponseData(request){
	var root = request.responseXML;
	var datatype = root.getElementsByTagName("type")[0].firstChild.nodeValue;
	var elements = new Array();
	var regChars = "";
	var selectedChar = null;
	elements = root.getElementsByTagName("element");
	if(root.getElementsByTagName("register").length > 0){
		regChars = root.getElementsByTagName("register")[0].firstChild.nodeValue;
		if(root.getElementsByTagName("register")[0].attributes.getNamedItem("selected") != null)
			selectedChar = root.getElementsByTagName("register")[0].attributes.getNamedItem("selected").value;
	}
	
	if (root.getElementsByTagName("countryInfo").length > 0) {		
				initCountryInfo( root.getElementsByTagName("countryInfo")[0] );
	}	
	
	switch(datatype) {
		case "countries":
			initCountries(elements, regChars, selectedChar);
			break;
		case "cities":
			initCities(elements, regChars);			
			break;
		case "branches":
			initBranches(elements);
			break;
		case "division":
			initDivision(elements);
			break;
		default:
			if(debugmode)
				alert("No proper datatype was found!");
	}
	
}

function initCountries(elements, regChars, selectedChar){
	if($("select_country") != null && elements != null && elements.length > 0) {
		var box = $("select_country");
		if(regChars.length > 0) {
			regObjCountry = new Register(box, elements, regChars, $("register_country"));
			regObjCountry.initRegister();
			regObjCountry.change(selectedChar||'A');
			regObjCountry.initOptions();			
			$("register_country").show();
			
		} else {
			for(i = 0; i < elements.length; i++)	{
				var _value = elements[i].getElementsByTagName("value")[0].firstChild.nodeValue;
				var _label = elements[i].getElementsByTagName("label")[0].firstChild.nodeValue;
				box.options[i] = new Option(_label, _value);
			}
			regObjCountry = null;
			$("register_country").hide();
		}
		Event.observe(box, 'change', boxEvent, false);
	}
         
}

function initCities(elements, regChars){ 
	if($("select_city") != null && elements != null) {                
		var box = $("select_city");
		if(elements.length >= _showCityRegisterNumber && regChars.length > 0) {
			$("register_city").show();
			regObjCity = new Register(box, elements, regChars, $("register_city"));
			regObjCity.initRegister();
			regObjCity.initOptions();									
			regObjCity.change(regChars.charAt(0));			
		} else {
			for(i = 0; i < elements.length; i++)	{
				var _value = elements[i].getElementsByTagName("value")[0].firstChild.nodeValue;
				var _label = elements[i].getElementsByTagName("label")[0].firstChild.nodeValue;
				box.options[i] = new Option(_label, _value);
			}
			regObjCity = null;
			$("register_city").hide();
		}
		Event.observe(box, 'change', boxEvent, false);
		$("display_city").show();  
    $("select_city").selectedIndex = -1;           
	} else {
		if(debugmode) 
			throw("initBranches: 'select_city' or 'elements' is null");
	}
}

function initBranches(elements){ 
	if($("select_branch") != null && elements != null && elements.length > 0) {
		var box = $("select_branch");
		for(i = 0; i < elements.length; i++) {
			var _value = elements[i].getElementsByTagName("value")[0].firstChild.nodeValue;
			var _label = elements[i].getElementsByTagName("label")[0].firstChild.nodeValue;
			box.options[i] = new Option(_label, _value);
		}
		changeSize("select_branch", elements.length);  
		Event.observe(box, 'change', boxEvent, false);
		$("display_branch").show();
	} else {
		if(debugmode) 
			throw("initBranches: 'select_branch' or 'elements' is null");
	}
}

function initDivision(elements){
	if($("display_division") != null && elements != null && elements.length > 0) {
		var box = $("display_division");
		for(i = 0; i < elements.length; i++) {
                    var text = "";
                    if (elements[i].childNodes.length > 1) {
                         for(j = 0; j < elements[i].childNodes.length; j++) {                         
                              text += elements[i].childNodes[j].nodeValue;                              
                         }
                    } else {
                         text = elements[i].firstChild.nodeValue;
                    }
			box.innerHTML = text;
		}
		box.show();
	} else {
		if(debugmode) 
			throw("initDivision: 'display_division' or 'elements' is null");
	}
}

function initCountryInfo(element) {
	if($("country_description") != null && element != null) {
		var show = false;
		for(i=0; i < element.childNodes.length; i++){
			node = element.childNodes[i];
			if(node.hasChildNodes()){
				Element.update(((node.nodeName == "description")?'countryDesc':node.nodeName), node.firstChild.nodeValue); 
				show = true;
			}
		}
		if(show)
			$("country_description").show();
	} else {
		if(debugmode) 
			throw("initBranches: 'country_description' or 'element' is null");
	}
}

function resetBox(box){
	while (box.hasChildNodes())
		box.removeChild(box.firstChild);
}

function reset(type){
	switch(type){
		case "country":
			resetBox($("select_country"));
			break;
		case "city":
			resetBox($("select_city"));
			$("register_city").hide();
			$("display_city").hide();
			break;
		case "branch":
			resetBox($("select_branch"));
			$("display_branch").hide();
			break;
		case "division":
			$("display_division").innerHTML = "";
			$("display_division").hide();
			break;
		case "country_description":		  
			$("headline").innerHTML = "";
			$("image").innerHTML = "";
			$("countryDesc").innerHTML = "";
			$("url").innerHTML = "";
			$("country_description").hide();
			break;
		default:
			if(debugmode) throw("reset: No proper type was found!");
	}
}

function showError(){
	obj = document.createElement('a');
    obj.href = 'error.do?width=350&height=150';
    lb = new Lightbox(obj);
    lb.activate();
}
function hideError(){
	Ajax.activeRequestCount--;
   Element.hide('systemWorking');
	Lightbox.deactivateBox();
}

function init(){
	var qp = new QueryParser(window.location.search);
	if(qp.getValue('country') != null) {
	  changeSize("select_country", 1);
		loadData("countries", "countryname=" + qp.getValue('country'));
		loadData("cities", "countryname=" + qp.getValue('country'));         
	} else {
		loadData("countries", "");
	}
}
Event.observe(window, 'load', init, false);

/* print version */
function printVersion() {
	$('locationfrm').action = 'print.do';
	$('locationfrm').target = 'printPopup';
	popup = window.open ('', $('locationfrm').target, 'width=635,height=600,scrollbars=yes,resizable=no');
	$('locationfrm').submit();
	popup.focus();
	$('locationfrm').action='#';
	return false;
}

function loadDataByFlash(countryname) {
	reset("country");
	reset("city");
	reset("branch");
	reset("division");
	
	if(countryname != null) {
		loadData("countries", "countryname=" + countryname);
   	loadData("cities", "countryname=" + countryname);    	    	    	
   	changeSize("select_country", 1);          
	} else {
		loadData("countries", "");
	}
}

function loadDataByFlashID(locID) {
	var c;
	for(i = 0; i < regObjCountry.elements.length; i++) {
		var tmp = regObjCountry.elements[i];
		var _value = tmp.getElementsByTagName("value")[0].firstChild.nodeValue;
		var _label = tmp.getElementsByTagName("label")[0].firstChild.nodeValue;
		
		if (_value == locID) {
			c = _label;
			break;
		}
		
	}
	if (c) loadDataByFlash(c);
}
