
/**
* Debug var
*/
var InCamps_debugMode = false;
/**
* Global wrapping function for smaller file size
*/
function _gel(ident) {
	var el;
	try{el=document.getElementById(ident);}catch(e){
		alert("Element does not exist.\n"+e.name+":"+e.message);
	}
	return el;
}
/*
* Class Core je zakladni trida obsahujici knihovni funkce javascriptu
* core bude slouzit jako prototype globalnimu objektu
*/
/**
 * @class InCamps_Core je zakladni trida obsahujici knihovni funkce javascriptu. Budou ji dedit vsechny obejkty, ktere chteji mit pristup do vsech knihovnich funkci
 * @param {Boolean} debug Slouzi k potlacovani error hlasek na konzoli
 * @version 1.0
 * @author Jan Pojer
 * @constructor
 */
function InCamps_Core(debug) {
	/*
	* definovani metod objektu, na zacatku pouze tech ktere jsou pouzivany
	*/
	this.debug = debug;
	
	/**
	* Fce zobrazuje errory
	* @param {String} message Zprava, ktera se ma zobrazit
	* @throws Error Na zaklade nastaveni debug parametru muze byt hlaska potlacena pouze na konzoli (debug_mode=false) jinak vyhazuje alert
	* @member InCamps_Core
	*/
	this.showError = function (message) {
		if(this.debug===true) {
			alert('UserError: '+message);
		}else{
			throw new Error('UserError: '+message);
		}
	};
	
	/**
	* Fce zobrazuje vsechny attributy objektu
	* @param {Object} obj Objekt jehoz attributy maji byt zobrazeny
	* @member InCamps_Core
	*/
	this.listProperties = function(obj) {
		var str="";
		for(var att in obj) str+=att+"\n";
		alert(str);
	};

	/**
	* Fce ziskava hodnotu selectu v zavislosti na id elementu
	* @param {String} id Id elementu
	* @member InCamps_Core
	*/
	this.getSelectValue = function(id) {
		return _gel(id).options[_gel(id).selectedIndex].value;
  };
  
  /**
	* Fce nastavuje hodnotu selectu v zavislosti na id elementu a zadane hodnote
	* @param {String} id Id elementu
	* @param {String} val Nova hodnota selectu
	* @member InCamps_Core
	*/
  this.setSelectValue = function(id,val) {
		for(var k=0; k<_gel(id).options.length; k++) {
			if (_gel(id).options[k].value == val) {
				_gel(id).options[k].selected = true;
			}
		}
	};
	
	this.L_gIV = L_gIV;
	this.L_aC = L_aC;
	this.L_rC = L_rC;
	this.L_hC = L_hC;
	this.L_gPNBTN = L_gPNBTN;
	this.L_gNSBTN = L_gNSBTN;
	this.L_gPSBTN = L_gPSBTN;
	this.L_gFCBTN = L_gFCBTN;
	this.L_gOT = L_gOT;
	this.L_gOL = L_gOL;
	this.L_aR = L_aR;
	this.L_aRD = L_aRD;
	this.L_aRSend = L_aRSend;
	this.L_aUE = L_aUE;
	
	/*TODO AJAX params*/
	
}

/**
 * @class Trida Item reprezentuje jeden konfiguracni element (element je prvek, kteremu jsou setovany handlery)
 * @param {String} id Id elementu v html formulari
 * @param {Handler} handler InCamps_Handler, ktery v sobe nese informace o handlerech objektu
 * @version 1.0
 * @author Jan Pojer
 * @constructor
 * @base InCamps_Core
 */
function InCamps_Item(id, handler) {
	this.id = id;
	if( handler instanceof InCamps_Handler) {
		this.handler = handler;
	}
  else if (handler==null) {
  }
  else{
		this.showError('Predany objekt neni typu InCamps_Handler (Item object)');
	}
	
	/**
	* Fce prirazuje handlery k udalostem. Prochazi pole events, ktere je soucasti kazdeho InCamps_Handler objektu ulozeneho v objektu InCamps_Item. Na zaklade idecka priradi elementu danou udalost.
	* @throws Error Na zaklade nastaveni debug parametru muze byt hlaska potlacena pouze na konzoli (debug_mode=false) jinak vyhazuje alert
	* @member InCamps_Core
	*/
	this.attachHandlers = function() {
		try {
			for(var handler in this.handler.events) {
				var el=_gel(this.id);
				el[handler] = this.handler.events[handler];
			}
		} catch (e) {
			this.showError(e.name+": "+e.message+"("+this.id+")");
		}
	}
}
InCamps_Item.prototype = new InCamps_Core(InCamps_debugMode);
InCamps_Item.prototype.contructor = InCamps_Item;

/**
 * @class Trida InCamps_Handler reprezentuje kolekci handleru pro dany element (element je prvek, kteremu jsou setovany handlery). Kazdy handler je prirazen spolecne s akci ktere ma byt pridelen.InCamps_Handler objekt lze inicializovat tremi zpusoby.
 * 1. new InCamps_Handler() - bez parametru
 * 2. new InCamps_Handler('onclick', f) - s prirazenim 1 handleru (f na akci onclick)
 * 3. new InCamps_Handler([['onclick', f],['onchange', ff]]) - tato moznost se hodi v pripade prirazeni nekolika handleru jednomu elementu
 *
 * @param {String|Array} ev Udalost, ktere se ma handler priradit (onclick|onchange|onKeyUp|onKeyDown....)
 * @param {Function} handler Funkce handleru.
 * @version 1.0
 * @author Jan Pojer
 * @constructor
 * @base InCamps_Core
 */
function InCamps_Handler(ev, handler) {
	/*
	* @member InCamps_Handler
	* Promenna udrzuje pole udalost=>handler
	*/
	this.events = new Array();
	
	/**
	* Fce přidává handler k dane udalosti do this.events
	* @param {String} ev Udalost, ktere se ma handler priradit (onclick|onchange|onKeyUp|onKeyDown....)
    * @param {Function} handler Funkce handleru.
	* @throws Error Na zaklade nastaveni debug parametru muze byt hlaska potlacena pouze na konzoli (debug_mode=false) jinak vyhazuje alert
	* @member InCamps_Handler
	*/
	this.addEvent = function(ev, handler) {
		if(typeof this.events[ev] == "undefined") {
			this.events[ev] = handler;
		}else{
			this.showError('K dane udalosti jiz byl handler prirazen (Handler object)');
		}
	};
	
	/*
	* Na zaklade poctu parametru se vykonava dana operace
	*/
	if(InCamps_Handler.arguments.length==2) {
		if(typeof ev == "string" && handler instanceof Function) {
			this.events[ev] = handler;
		}else{
			this.showError('Predany objekt neni typu String nebo Function (Handler object)');
		}
	}else if(InCamps_Handler.arguments.length==1 && ev instanceof Array){
		for(var i in ev) {
			this.addEvent(ev[i][0],ev[i][1]);
		}
	}
}
InCamps_Handler.prototype = new InCamps_Core(InCamps_debugMode);
InCamps_Handler.prototype.contructor = InCamps_Handler;

/**
* @class Trida InCamps_DefaultData ma za ukol naplnit formular daty ziskanymi z databaze (nastaveni v zao)
*
* @version 1.0
* @author Jan Pojer
* @constructor
* @base InCamps_Core
*/
function InCamps_DefaultData() {
	this.fill = function() {
	};
}
InCamps_DefaultData.prototype = new InCamps_Core(InCamps_debugMode);
InCamps_DefaultData.prototype.contructor = InCamps_DefaultData;

/**
 * @class Global je trida definujici hlavni funkcnost. Obsahuje paramatry i handlery 
 *
 * @version 1.0
 * @author Jan Pojer
 * @constructor
 * @base InCamps_Core
 */
function InCamps_Glob() {
	/*
	* config obsahuje vsechny konfiguracni paramatry dynamicky loadovane pomoci ws (fetch ze zao)
	*/
	this.config = new Object();
	/*
	* handlers obsahuje vsechny handlery pouzite na formulari
	*/
	this.handlers = new Object();
	/* origin0 onchange handler */
//	this.handlers.AO2s12dSoCh = AO2s12dSoCh;
	/*
	* seznam globalnich parametru
	*/
	this.config.global = new Object();
	/*
	* seznam prvku na formulari ke kterym se ma pripichnout handler na onloadu
	*/
	this.config.items = new Object();
	/*ticket type*/
	this.config.items.flagfaceimg = new InCamps_Item('flagfaceimg', null);
	this.config.items.flagfaceimgsmall = new InCamps_Item('flagfaceimgsmall', null);
  this.config.items.menu = new Object();

//	this.config.items.origin0 = new InCamps_Item('AO2_StepOne2_origin_0', new InCamps_Handler([['onchange', this.handlers.AO2s12dSoCh], ['onkeyup', this.handlers.AO2Empty]]));

	/*
	* initialization
	*/
	this.init = function(www) {
		if (this.init.arguments.length!=1) {
			this.showError('Musite zadat adresu proxy serveru');
		}
		/*TODO check for www input*/
		this.config.ajax = new Object();
		this.config.ajax.kde = www;
		this.config.url = www;
		/*attach handlers*/

		for (var item in this.config.items) {
			if (this.config.items[item] instanceof InCamps_Item) {
				//if (i==1) {alert(this.config.items[item].id);i++}
				if(this.config.items[item].handler!=null) this.config.items[item].attachHandlers();
			}
		}
		/*init default values*/
    this.imagePreload(this.config.global.acceptLang);    
		/*
		* default obsahuje fce, ktere naplnuji formular default daty
		*/
		this.defaultData = new InCamps_DefaultData();
		this.defaultData.fill();
				
	}
  
  this.imagePreload = imagePreload;
  this.swapImage = swapImage;
  this.swapSmallImage = swapSmallImage;
  this.backgroundIn=backgroundIn;
  this.backgroundOut=backgroundOut;  
}
InCamps_Glob.prototype = new InCamps_Core(InCamps_debugMode);
InCamps_Glob.prototype.contructor = InCamps_Glob;

/***********************************************************************************************************************
* FUNCTIONS
*/


function L_gIV(formItem, name) {
  var i;
  var ret = false;
  formItem = L_gPNBTN(formItem, 'FORM');
  if (formItem) {
    var inputs = formItem.getElementsByTagName('INPUT');
    for (i = 0; i < inputs.length; i++) {
      if (
          (inputs[i].type != 'radio') &&
          (inputs[i].type != 'checkbox') &&
          (inputs[i].name == name)
         ) {
        ret = inputs[i].value;
        break;
      }
    }
  }

  return ret;
}

function L_aC(el, cl) {
  el.className += (el.className ? ' ' : '') + cl;
}

function L_rC(el, cl) {
  var classesOld = el.className.split(' ');
  var classesNew = new Array();
  var i;
  
  for (i in classesOld) {
    if (classesOld[i] != cl) {
      classesNew.push(classesOld[i]);
    }
  }
  el.className = classesNew.join(' ');
}

function L_hC(element, classes, separator){
    var sep =  separator ? separator : ' ';
    var parts = new Array();
    if (!isNaN(sep)){
      parts[0] = element.className.substring(0, sep);
      parts[1] = element.className.substring(sep);
    }
    var parts = element.className.split(sep);
    if (!classes) {return parts;}
    for (var index in parts){
      if (parts[index] == classes) {return true;} 
    }
    return false;
};

function L_gPNBTN(element, name) {
  element = element.parentNode;
  while (element && element.nodeName != name) {
    element = element.parentNode;
  }
  return element;
}

function L_gNSBTN(element, name, count) {
  if (!count) { count = 1; }
  do {
    element = element.nextSibling;
    if (element && element.nodeName == name) { count--; }
  } while (element && ((element.nodeName != name) || (count != 0)));
  return element;
}

function L_gPSBTN(element, name) {
  element = element.previousSibling;
  while (element && element.nodeName != name) {
    element = element.previousSibling;
  }
  return element;
}

function L_gFCBTN(element, name) {
  element = element.firstChild;
  while (element && element.nodeName != name) {
    element = element.nextSibling;
  }
  return element;
}

function L_gOT(el) {
	var offsetTop = 0;
	if (el.offsetParent) {
		offsetTop = el.offsetTop
		el = el.offsetParent;
		while (el) {
			offsetTop += el.offsetTop;
			el = el.offsetParent;
		}
	}                                     
	return offsetTop;
}

function L_gOL(el) {
	var offsetLeft = 0;
	if (el.offsetParent) {
		offsetLeft = el.offsetLeft
		el = el.offsetParent;
		while (el) {
			offsetLeft += el.offsetLeft
			el = el.offsetParent;
		}
	}                                     
	return offsetLeft;
}

/** Ajax Library functions **/

var LV_aR = new Array();
var LV_aRO = new Array();
var LV_aRPostData = new Array();

function L_aR(type, url, handler, element, delay, post) {
  var httpRequest = false;
  post = post ? 1 : 0;
  var postData = null;

  if (post) {
    var urlDataStart = url.indexOf('?');
    if (urlDataStart > -1) {
      postData = url.substring(urlDataStart + 1, url.length);
      url = url.substring(0,urlDataStart);
    }
  }

  if (window.XMLHttpRequest) {
    httpRequest = new XMLHttpRequest();
    if (httpRequest.overrideMimeType) {
      httpRequest.overrideMimeType('text/xml');
    }
  } else if (window.ActiveXObject) { 
    try {
      httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {}
    }
  }

  if (httpRequest) {
    var ident = Math.random();
    LV_aR[type] = ident;
    LV_aRO[type] = httpRequest;
    LV_aRPostData[ident] = postData;
    httpRequest.onreadystatechange = function () { handler(httpRequest, type, ident, element); };
    httpRequest.open(post ? 'POST' : 'GET', url, true);
    if (!delay) {
      L_aRSend(httpRequest, post, postData);
    } else {
      window.setTimeout("L_aRD('"+ type +"','"+ ident +"',"+ post +");", delay);
    }
  }
}

function L_aRD(type, ident, post) {
  if (LV_aR[type] == ident) {
    L_aRSend(LV_aRO[type], post, LV_aRPostData[ident]);
  }
}

function L_aRSend(httpRequest, post, postData) {
  if (post) {
    httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    httpRequest.setRequestHeader("Content-length", postData.length);
    httpRequest.setRequestHeader("Connection", "close");
  }
  httpRequest.send(postData);
}

function L_aUE(val) {
  var ret = val.toString();
  return encodeURIComponent(ret);
}

/*define fnctions*/
function imagePreload(accept_languages) {
  for (var item in accept_languages) {
			  InCamps_Glob.config.global.acceptLang[item].img=new Image();
        InCamps_Glob.config.global.acceptLang[item].img.src = "../images/faces/"+item+".jpg";
		}
  InCamps_Glob.config.items.menu.who = new Image();
  InCamps_Glob.config.items.menu.who.src = "../images/btnWhoUp.png";
  InCamps_Glob.config.items.menu.how = new Image();
  InCamps_Glob.config.items.menu.how.src = "../images/btnHowUp.png";
  InCamps_Glob.config.items.menu.where = new Image();
  InCamps_Glob.config.items.menu.where.src = "../images/btnWhereUp.png";
  InCamps_Glob.config.items.menu.what = new Image();
  InCamps_Glob.config.items.menu.what.src = "../images/btnWhatUp.png";
}
function swapImage(swin) {
  var imgframe=_gel(this.config.items.flagfaceimg.id);
  imgframe.src=this.config.url+"/images/faces/"+swin+".jpg";
}
function swapSmallImage(swin) {
  var imgframe=_gel(this.config.items.flagfaceimgsmall.id);
  imgframe.src=this.config.url+"/images/faces/"+swin+"_small.jpg";
}
function backgroundIn(el, ident) {
  var parent;
  var btnEl = document.getElementById("btn"+ident);
  var imgs = btnEl.getElementsByTagName("img");
  parent=el.parentNode;
  parent.style.backgroundColor='#a70304';
  imgs[0].src=this.config.url+"/images/btn"+ident+"Up.png";
}
function backgroundOut(el, ident) {
  var parent;
  var btnEl = document.getElementById("btn"+ident);
  var imgs = btnEl.getElementsByTagName("img");
  parent=el.parentNode;
  parent.style.backgroundColor=null;
  imgs[0].src=this.config.url+"/images/btn"+ident+".png";
}
/*FUN start!!!s*/
var InCamps_Glob = new InCamps_Glob();
//global.listProperties(global.config.items.origin1.handler.events);



