// $Id: framework.js 4 2008-07-20 16:35:51Z fedot $
var $ = function(){
	return $.init.call(arguments[0],arguments[0]);
};
var Utils = Utils || {};

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]);
	}
}

// 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);
};
/*
 *
// http://ejohn.org/blog/getelementsbyclassname-speed-comparison/
// http://snook.ca/archives/javascript/your_favourite_1/
// https://developer.mozilla.org/en/DOM/document.getElementsByClassName
// https://developer.mozilla.org/en/DOM/Document.evaluate
*/
function gebcn(){
	if (document.getElementsByClassName){
		// NOTE: try Native
		gebcn = _ntv_gebcn;
	} else if (document.evaluate){
		// NOTE: use XPath than available
		gebcn = _xp_gebcn;
	} else {
		// NOTE: if no Native and XPath try DOMwalk

	}
	return gebcn.apply(this,arguments);
}

function _ntv_gebcn(){
	var root = this.nodeType?this:document;
	var tag = arguments[0] || '*';
	var resultNodes = [];
	var classes = Array.prototype.slice.call(arguments,1);
	var tags = root.getElementsByTagName(tag);
	for (var t = 0, tlen = tags.length; t < tlen; t++) {
		var rtag = tags[t];
		for (var i = 0, len = classes.length; i < len; i++) {
			var elms = rtag.getElementsByClassName(classes[i]);
			for (var j = 0, jlen = elms.length; j < jlen; j++)
				resultNodes.push(elms[i]);
		}
	}
	return resultNodes;
}

function _xp_gebcn(){
	var root = this.nodeType?this:document;
	var tag = arguments[0] || '*';
	var resultNodes = [];
	var classes = Array.prototype.slice.call(arguments,1);
	for (var i = 0, len = classes.length; i < len; i++) {
		var xpathResult = document.evaluate('//'+ tag +'[@class = "' + classes[i] + '"]', root, null, 0, null);
		var item = xpathResult.iterateNext();
		while (item) {
			resultNodes.push(item);
			item = xpathResult.iterateNext();
		}
	}
	return resultNodes;
}

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 && 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);
}

function stopEvt(e){
  if (!e) var e = window.event;
  e.cancelBubble = true;
  if (e.stopPropagation) e.stopPropagation();
}

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;
}

function customer_fun(){
	var customers_block = dd('div','customers_icons');
	if (!customers_block.length) return;
	customers_block[0].style.display='';
	var icons = dd('a','customer_icon_holder');
	var start_m = -350;
	timers.add(function(){
			for (var i=0;i<icons.length;i++){
				icons[i].style.marginTop = start_m+'px';
			}
			start_m+=3;
			if (start_m>=0) return false;
	});
}
//$.ready(customer_fun);

function user_login(){
	var login_box = d('userlogin_box'), start_h=0,total=20;
	if (login_box && login_box.style.display=='none') {
		login_box.style.overflow = 'hidden';
		login_box.style.display = '';
		timers.add(function(){
			login_box.style.height = start_h+'px';
			start_h+=2;
			if (start_h > total) {
				login_box.style.overflow = '';
				//login_box.style.height = '';
				var uname = dd.call(login_box,'input','login_field')[0] || {focus:function(){}};
				uname.focus();
				return false;
			}
		});
	} else {
		if (login_box) {
			login_box.style.display = 'none';
			login_box.style.height = 0;
		}
	}
}

function open_in_popup (popup_title, req_url) {
	document.getElementById('spop').style.left='30px';
	document.getElementById('t_win1').style.width='750px';
	document.getElementById('spop').style.width='750px';
	document.getElementById('popup_content').style.height='400px';
    document.getElementById('popup_title').innerHTML=popup_title;
	document.getElementById('spop').style.visibility='visible';
	xmlreq_put(req_url,'popup_content');
}

/**
 * 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)];
}

function hasClass(ele,cls) {
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

function addClass(ele,cls) {
	if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}

function removeClass(ele,cls) {
	if (hasClass(ele,cls)) {
		var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		ele.className=ele.className.replace(reg,' ');
	}
}


/**
 * Debug functionality
 */

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

//String.prototype.trim = function(){return this.replace(/^\s+|\s+$/g,'');}
String.prototype.trim = function(chrs){
	var whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
    var chrs = (chrs || whitespace).split('');
    var res = this.replace('','');
	while (chrs.indexOf(res[0])!=-1 || chrs.indexOf(res[res.length-1])!=-1){
	    for (var i=0;i<chrs.length;i++){
	        var c = chrs[i].replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/,"\\$1");
	        var r = new RegExp('^'+c+'+|'+c+'+$','g');
	        res = res.replace(r,'');
	    }
	}
    return res;
}

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

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 init_page(){}

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


function tab_switch(th){
	var handle = th;
	var tab = d(th.id.replace('_handle',''));
	if ( hasClass(handle,'selected') ) return false;

	var selected_tab = dd.call(handle.parentNode,'div','selected')[0];
	addClass(handle,'selected');

	removeClass(selected_tab,'selected');
	var all_tab_content = dd.call(tab.parentNode,'div','tab-content');
	for (var i=0;i<all_tab_content.length;i++){
		addClass(all_tab_content[i],'hidden');
	}
	removeClass(tab,'hidden');
	//clog(handle,tab);
}

function print_content(){
	window.print();
	return false;
}
