// NOTE: based partially on ela2-dev system...
var $ = function(){
	return $.init.call(arguments[0],arguments[0]);
};

var isIE = 0 //@cc_on+1;

//use background cache in IE6
if (isIE) try{document.execCommand("BackgroundImageCache", false, true);}catch(err){}
	
$.init = function(el){
	for (var i in SigMagic){
		var callfunc = SigMagic[i];
		el[i] = function (){return callfunc.apply(el,arguments);}
	}
	return el;
}

$.ready = function(func){
	if (typeof func=='function') set_evt(window,'load',func);
}

/**
 * Some nice magic...
 * NOTE: Since IE doesn't support extending of Node and Element prototypes we wrap this functionality with a trick...
 */

SigMagic = {
	_data:	function(data_name,data_val){
			//clog(this,arguments);
			var data_name = 'data-'+data_name;
			var data_val = data_val || null;
			if (data_val==null){
				return this.getAttribute(data_name) || null;
			} else return this.setAttribute(data_name,data_val);
		}
}

function val_constructor(){
	for(i=0;i<arguments.length;i++){
		var tmp = arguments[i];
		var prepared = Array();
		if (typeof(tmp)=='string'){
			prepared = tmp.split(',');
		} else {
			prepared = tmp;
		}
		for(j=0;j<prepared.length;j++) $[prepared[j]] = d(prepared[j]);
	}
}

function menuhighlight(mi) {
    //alert(mi.id);

    var topsub = document.getElementById('sub_menu');
    topsub.innerHTML='&nbsp;';
    if (mi.parentNode.lastChild.nodeName=='UL'){
	if ($['selmenu']){
		$['selmenu'].className='';
		$['selmenu'] = '';
		$['selmenu'] = mi;
		$['selmenu'].className = 'selected';
	} else {
		$['selmenu'] = mi;
		$['selmenu'].className = 'selected';
	}
	    var submenu = mi.parentNode.lastChild;
	    topsub.insertBefore(submenu.cloneNode(true),topsub.firstChild);
    } else{
	if ($['selmenu']){
		$['selmenu'].className='';
		$['selmenu'] = '';
	}
	    topsub.innerHTML='<ul class="submenu"><li class="submenu_item" id="menu_last">&nbsp;</li></ul>';
    }
}

function flash_submenu() {
	var sm = document.getElementById('sub_menu');
	sm.style.backgroundColor='#6fa9ed';
	changecss('li.submenu_item a','color','white');
	setTimeout(function(){ sm.style.backgroundColor=''; changecss('li.submenu_item a','color','#636466'); },1000);
}
// http://www.shawnolson.net/scripts/public_smo_scripts.js
function changecss(theClass,element,evalue) {
	var cssRules;
	if (document.all) {
		cssRules = 'rules';
	}
	else if (document.getElementById) {
		cssRules = 'cssRules';
	}
	for (var S = 0; S < document.styleSheets.length; S++){
		for (var R = 0; R < document.styleSheets[S][cssRules].length; R++) {
			if (document.styleSheets[S][cssRules][R].selectorText == theClass) {
				document.styleSheets[S][cssRules][R].style[element] = evalue;
				
			}
		}
	}	
}
	
function ajax_login(target_url) {
	var lw = d('login_window');

	var target_el_node = lw.parentNode.parentNode;


	var target_el = 'login_window';
	
	if (target_el_node.nodeName == 'DIV' || target_el_node.nodeName == 'TD') {
		var target_el = target_el_node.id;
	}

	var t = d(target_el);

	setTimeout(function(){ 
		t.innerHTML = '<div align="left"><img border="0" src="/ui2/images/loading.gif"> <b style="color:darkred;">Authenticating...</b></div>'; 
	},500);

	setTimeout(function(){
		if (target_el == 'page_content' || target_el == 'login_window' || target_el == '') {
			t.innerHTML = '<div align="left"><img border="0" src="/ui2/images/loading.gif"> <b style="color:darkred;">Redirecting...</b></div>'; 
			location.href = target_url;
		} else {
			xmlreq_put(target_url,target_el);
		}
	},2000);
}

function d(node_id){
	return typeof node_id=='object'?node_id:(document.getElementById(node_id) || false);
};

function dd(){
	var startpoint = document;
	if (this && this.nodeType){
		var startpoint = this;
	}
	var block = (arguments[0]+'').toUpperCase();
	if (!block) return;
	var result_nodes = Array();
	var nodes = startpoint.getElementsByTagName(block);
	for (var node=0;node<nodes.length;node++){
		if (arguments.length>1){
			//clog(arguments);
			for (i=1;i<arguments.length;i++){
				var classlong = (nodes[node].className || '').split(' ');
				for (var k=0;k<classlong.length;k++)
					if (classlong[k] == arguments[i]) result_nodes.push(nodes[node]);
			}
		} else {
			if (nodes[node].nodeName==block) result_nodes.push(nodes[node]);
		}
	}
	return result_nodes;
}

function set_evt_by_class(tagname, classname, eventname, event_func){
	var nodes = dd.call(this,tagname,classname);
	for (i=0;i<nodes.length;i++)
		set_evt(nodes[i],eventname,event_func);
}

function uset_evt_by_class(tagname, classname, eventname, event_func){
	var nodes = dd.call(this,tagname,classname);
	for (i=0;i<nodes.length;i++)
		uset_evt(nodes[i],eventname,event_func);
}

function t(e){
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3)
		targ = targ.parentNode;
	return targ;
}

function set_group_evt(el,events){
	for (var event in events)
		if (typeof event=='string' && typeof events[event]=='function')
			set_evt(el,event,events[event]);
}

function set_evt(el,evt,func){
	if (typeof evt=='object'){return set_group_evt(el,evt)}
	if (el.addEventListener){
		el.addEventListener(evt,func,false);
		return true;
	} else if (el.attachEvent) return el.attachEvent("on"+evt,func);
}

function uset_evt(el,evt,func){
	if (el.removeEventListener){
		el.removeEventListener(evt,func,false);
	} else if (el.detachEvent) return el.detachEvent("on"+evt,func);	
}

var timers = {
    timerID: 0,
    timers: [],
    start: function(){
        if (this.timerID) 
            return;
        (function(){
            for (var i = 0; i < timers.timers.length; i++) 
                if (timers.timers[i]() === false) {
                    timers.timers.splice(i, 1);
                    i--;
                }
            timers.timerID = setTimeout(arguments.callee, 0);
        })();
    },
    stop: function(){
        clearTimeout(this.timerID);
        this.timerID = 0;
    },
    add: function(fn){
        this.timers.push(fn);
        this.start();
    }
};

var ms_XMLHTTP = '';
var global_request = false;
function xmlreq_post(sURL) {
	if (!global_request){
		var request=null;
		if (window.XMLHttpRequest) {
			request=new XMLHttpRequest();
		} else if (window.ActiveXObject){
			if (ms_XMLHTTP) {
				request = new ActiveXObject(ms_XMLHTTP);
			} else {
				var versions = ["Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
				for (var i = 0; i < versions.length ; i++) {
					try {
						request = new ActiveXObject(versions[i]);
						if (request) {ms_XMLHTTP = versions[i]; break;}
					}
					catch (e){}
				}
			}
		}
		global_request = request;
	}
	if(!global_request) return ""; // if browser doesn't support XMLHTTP return empty string
	global_request.open("GET", sURL, false);
	global_request.send(null);
	return global_request.responseText;
}


    function xmlreq_put(url,to_where) {
		var argv = xmlreq_put.arguments;
		var on_compl = '' + argv[2];

		if (to_where=='basket') {
		    var bmw = d('bmw').value;
		    if (bmw>645) {
			url = url + '&bmw=' + bmw;
		    }
		}

		var tw=document.getElementById(to_where);
		var ch1=tw.offsetHeight;
		var ch2=tw.offsetWidth;

		tw.innerHTML = '<table height="'+ch1+'" width="'+ch2+'"><tr><td valign="top" align="left"><img border="0" src="/ui2/images/loading.gif"> <b style="color:darkred;">Loading...</b></td></tr></table>';

		setTimeout(function(){

			var http_request = false;

			if (window.XMLHttpRequest) { // Mozilla, Safari, ...
				http_request = new XMLHttpRequest();
				if (http_request.overrideMimeType) {
					http_request.overrideMimeType('text/xml');
					// See note below about this line
				}
			} else if (window.ActiveXObject) { // IE
				try {
					http_request = new ActiveXObject("Msxml2.XMLHTTP");
				} catch (e) {
					try {
						http_request = new ActiveXObject("Microsoft.XMLHTTP");
					} catch (e) {}
				}
			}

			if (!http_request) {
				alert('Giving up :( Cannot create an XMLHTTP instance');
				return false;
			}

			http_request.onreadystatechange = function() { applyContents(http_request,to_where,on_compl); };
			http_request.open('GET', url, true);
			http_request.send(null);

		},50);

    }

    function xmlreq_load(url,to_where,on_compl_f) {
      //alert('load: url=('+url+') target=('+to_where+') run=('+on_compl_f+')');

		setTimeout(function(){

			var http_request = false;

			if (window.XMLHttpRequest) { // Mozilla, Safari, ...
				http_request = new XMLHttpRequest();
				if (http_request.overrideMimeType) {
					http_request.overrideMimeType('text/xml');
					// See note below about this line
				}
			} else if (window.ActiveXObject) { // IE
				try {
					http_request = new ActiveXObject("Msxml2.XMLHTTP");
				} catch (e) {
					try {
						http_request = new ActiveXObject("Microsoft.XMLHTTP");
					} catch (e) {}
				}
			}

			if (!http_request) {
				alert('Giving up :( Cannot create an XMLHTTP instance');
				return false;
			}

			http_request.onreadystatechange = function() { applyContents(http_request,to_where,on_compl_f); };
			http_request.open('GET', url, true);
			http_request.send(null);

		},50);

    }

    function applyContents(http_request,where,on_complete_func) {
        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
                //alert(http_request.responseText);
            	var dest = d(where) || {};
				if (dest.nodeType) dest.innerHTML = http_request.responseText;
				if (typeof on_complete_func!='function'){
					eval(on_complete_func);
				} else {
					on_complete_func.call(dest,http_request.responseText);
				}
            } else {
                alert('There was a problem with the request.');
            }
        }
    }


// rightclick

var message;
message =           "The content of this web site may not be copied,\n";
message = message + "replaced, distributed, published, displayed, modified,\n";
message = message + "or transferred in any form or by any means except\n";
message = message + "with the prior permission of Signature IT Ltd.\n\n";
message = message + "Copyright infringement is a violation of federal law\n";
message = message + "and subject to criminal and civil penalties.\n\n";
message = message + "(C) 2007, Signature IT Ltd.\n\n";


function clickIE4(){
	if (event.button==2){
		alert(message);
		return false;
	}
}

function clickNS4(e){
	if (document.layers||document.getElementById&&!document.all){
		if (e.which==2||e.which==3){
			alert(message);
			return false;
		}
	}
}

if (document.layers){
	document.captureEvents(Event.MOUSEDOWN);
	document.onmousedown=clickNS4;
}
else if (document.all&&!document.getElementById){
	document.onmousedown=clickIE4;
}

document.oncontextmenu=new Function("alert(message);return false");







// This is variable for storing callback function
var ae_cb = null;

 
// this is a simple function-shortcut
// to avoid using lengthy document.getElementById
function ae$(a) { return document.getElementById(a); }





// This is a main ae_prompt function
// it saves function callback 
// and sets up dialog
function ae_prompt(cb, q, a) {
	ae_cb = cb;
	ae$('aep_t').innerHTML = document.domain + ' question:';
	ae$('aep_prompt').innerHTML = q;
	ae$('aep_text').value = a;
	ae$('aep_ovrl').style.display = ae$('aep_ww').style.display = '';
	ae$('aep_text').focus();
	ae$('aep_text').select();
}
 
// This function is called when user presses OK(m=0) or Cancel(m=1) button
// in the dialog. You should not call this function directly.
function ae_clk(m) {
	// hide dialog layers 
	ae$('aep_ovrl').style.display = ae$('aep_ww').style.display = 'none';
	if (!m)  
		ae_cb(null);  // user pressed cancel, call callback with null
	else
		ae_cb(ae$('aep_text').value); // user pressed OK 
}






 
// This is a main ae_popup function
// it saves function callback 
// and sets up dialog
function ae_popup(popup_title, popup_contents) {
	ae$('aep2_t').innerHTML = popup_title;
	ae$('aep2_text').innerHTML = popup_contents;
	ae$('aep2_ovrl').style.display = ae$('aep2_ww').style.display = '';
}
 
// This function is called when user presses OK(m=0) or Cancel(m=1) button
// in the dialog. You should not call this function directly.
function ae_popup_close() {
	// hide dialog layers 
	ae$('aep2_ovrl').style.display = ae$('aep2_ww').style.display = 'none';
}









var prompt_w_retval = null;
function prompt_w (quest, answ) {
	ae_prompt( prompt_wcb , quest , answ );
	var retval = prompt_w_retval;
	return (retval);
}
function prompt_wcb (user_inp) {
	prompt_w_retval = user_inp;
}

/**
 * AJAX
 */

function _map_get_args(obj){
	var res = '';
	for (i in obj) res += '&'+encodeURIComponent(i)+'='+encodeURIComponent(obj[i]);
	return res.replace(/^\&/,'?');
}

function do_ajax(url, vars, callbackFunction)
{
  var request = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0");
  request.open("POST", url, true);
  request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  request.onreadystatechange = function(){
    if (request.readyState == 4 && request.status == 200){
      if (request.responseText){
          callbackFunction(request.responseText);
      }
    }
  };
  request.send(vars);
}

/**
 * Traversing
 */

function nodeText(n){return n.textContent || n.innerText}

/**
 * Dimensions, Styling
 */

function rewriteCssName(cssName){
	var rewriten = cssName.split('-');
	// NOTE: first word are leaved lowercased as in CSS Specs
	for(var i=1;i<rewriten.length;i++){
		rewriten[i] = upper_word(rewriten[i]);
	}
	return rewriten.join('');
}

function _css(el,styleObject){
	if (typeof el!='object') {
		el = d(el);
		if (typeof el!='object') return;
	}
	for (var i in styleObject){
		el.style[rewriteCssName(i)] = styleObject[i];
	}
}

function _getTop(el){
	var ot=el.offsetTop;
	while((el=el.offsetParent) != null) {
		ot += el.offsetTop;
	}
	return ot;
}

function _getLeft(el){
	var ol=el.offsetLeft;
	while((el=el.offsetParent) != null) {
		ol += el.offsetLeft;
	}
	return ol;
}

function fadeTo(elem,value){
	if (isIE){
		elem.zoom = 1;
		elem.filter = (elem.filter || "").replace( /alpha\([^)]*\)/, "" ) +	(parseInt( value ) + '' == "NaN" ? "" : "alpha(opacity=" + value * 100 + ")");
	} else{
		elem.style.opacity = value;
	}
}

function _gcs(el,prop){
	var computedStyle;
	if (typeof el.currentStyle != 'undefined'){
		computedStyle = el.currentStyle;
	} else {
		computedStyle = document.defaultView.getComputedStyle(el, null);
	}
	return computedStyle[rewriteCssName(prop)];
}

/**
 * Debug functionality
 */
String.prototype.trim = function(){return this.replace(/^\s+|\s+$/g,'');}

function upper_word(word){
	  return word.substr(0,1).toUpperCase() + word.substr(1);
}

function clog(){
  var caller_name = (clog.caller+'').split(' ')[1].replace(/\(.*/,'') || 'anonymous';
  if (typeof console !="undefined"){
      console.log(caller_name,arguments);
  }
}

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(elt /*, from*/) {
    var len = this.length;
    var from = Number(arguments[1]) || 0;
    from = (from < 0) ? Math.ceil(from) : Math.floor(from);
    if (from < 0) from += len;
    for (; from < len; from++) {
      if (from in this && this[from] === elt) return from;
    }
    return -1;
  };
}


function uniq(){
	var prefix = '';
	if (arguments.length) prefix = arguments[0];
	return prefix+(new Date()).getTime();
}

 
function init_page(){
}

set_evt(window,'load',function(){init_page()});

