//$Id: framework.js 4 2008-07-20 16:35:51Z fedot $
// test change

target_url_override='';

jQuery.noConflict(); // removes $ from jquery and leaves it with framework
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);
		}
}

// JSON, for IE7 backwards compatibility:
/**
 * Implements JSON stringify and parse functions
 * v1.0
 *
 * By Craig Buckler, Optimalworks.net
 *
 * As featured on SitePoint.com
 * Please use as you wish at your own risk.
*
 * Usage:
 *
 * // serialize a JavaScript object to a JSON string
 * var str = JSON.stringify(object);
 *
 * // de-serialize a JSON string to a JavaScript object
 * var obj = JSON.parse(str);
 */

var JSON = JSON || {};

// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function (obj) {

	var t = typeof (obj);
	if (t != "object" || obj === null) {

		// simple data type
		if (t == "string") obj = '"'+obj+'"';
		return String(obj);

	}
	else {

		// recurse array or object
		var n, v, json = [], arr = (obj && obj.constructor == Array);

		for (n in obj) {
			v = obj[n]; t = typeof(v);

			if (t == "string") v = '"'+v+'"';
			else if (t == "object" && v !== null) v = JSON.stringify(v);

			json.push((arr ? "" : '"' + n + '":') + String(v));
		}

		return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
	}
};


// implement JSON.parse de-serialization
JSON.parse = JSON.parse || function (str) {
	if (str === "") str = '""';
	eval("var p=" + str + ";");
	return p;
};


function hasClass(elm,cls){
		var classy = cls || '';
		var re = new RegExp(' '+classy+' ');
    return re.test(' '+elm.className+' ');
}

function delClass(elm,cls){
    if (hasClass(elm,cls)){
         elm.className = (' '+(elm.className || '')+' ').replace(' '+cls+' ','').trim();
		}
}

function addClass(elm,cls){
    if (!hasClass(elm,cls))
        elm.className = (elm.className || '')+' '+cls;
}

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


/**
 * DEPRECATED. Do not use this function. use ajaxLogin instead.
 *
 * @param string target_url
 * @param bool ajax_caller (optional - undefined is valid)
 */
function ajax_login(target_url, ajax_caller) {
    var lw = d('login_window');

    var target_el_node = lw.parentNode.parentNode;


    var target_el = 'login_window';

    if ((ajax_caller == undefined) && (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;">'+tg("Authenticating...")+'</b></div>';
    },500);

    setTimeout(function(){
        if ((ajax_caller == undefined) && (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;">'+tg("Redirecting...")+'</b></div>';
            location.href = target_url;
        } else {
            xmlreq_put(target_url,target_el,ajax_caller);
        }
    },200);

}

/**
 * Perform embedded or redirected user login.
 *
 * @param form The form to submit
 * @param target_url The url to load once login is successful
 * @param use_ajax boolean True to force embedding result in page
 * @param object login_params optional parameters
 */
function ajaxLogin(form, target_url, use_ajax, login_params) {
    var $username_passw = jQuery(form).serialize(); // save it, before messing with the page

	var progress_report_target = jQuery("#login_window");

	var progress_report_target_container = progress_report_target.parent().parent();
	if ((!use_ajax) &&
			(progress_report_target_container.is("div") ||
			 progress_report_target_container.is("td"))) {
		progress_report_target = progress_report_target_container;
	}

	progress_report_target.html('<div class="login_progress_notification"><img src="/ui2/images/loading.gif">'+tg("Authenticating...")+'</div>');

	// The following tests are to force redirection even if ajax is requested.
	// Find what page we are on and choose to redirect accordingly
	var pages_with_redirect_after_submit = ["module_profile", "technical_library", "module_orders"];
    var on_login = Boolean(use_ajax);
	var force_redirect = false;
	jQuery(pages_with_redirect_after_submit).each(function(index, value) {
		if (jQuery("body").hasClass(value))
			force_redirect = true;
	});

    if (target_url_override) target_url = target_url_override;

    // use login paramaters
    if(typeof(login_params)==typeof({})) {
        if(typeof(login_params.force_redirect)!='undefined') {
            force_redirect = login_params.force_redirect;
        }
        if(typeof(login_params.post_login_func)==typeof(function(){})) {
            on_login = login_params.post_login_func;
        }
    }

	// Hack to check if the user is trying to add to favoriets and a login form appears.
	// Forces a redirect to the favorites page.
	if (target_url.indexOf("act=favadd&") != -1)
		force_redirect = true;

	jQuery.ajax({
		url: "/login_silent.php",
		type: "POST",
		data: $username_passw,
		success: function() {
			var target_elements = ["page_content", "login_window", ""];
			var redirect = jQuery.inArray(progress_report_target.attr("id"), target_elements) > -1;
			if (force_redirect || (!use_ajax && redirect)) {
				progress_report_target.html('<div class="login_progress_notification"><img src="/ui2/images/loading.gif">'+tg("Redirecting...")+'</div>');
				window.location.href = target_url;
                if(typeof(on_login)==typeof(function(){})) {
                    on_login.call();
                }
			} else {
				xmlreq_put(target_url, progress_report_target.attr("id"), on_login);
			}
		}
	});
	return false; // Prevent form from submitting normally
}

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 && 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 (typeof el=='object'){
        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;
}


/**
 * @param string url
 * @param string to_where id of target witch is content is been replaced.
 * @param bool|string replace_content/on_complete_func (optional), when set to TRUE the to_where tag is replaced by content, (see: ajax_login)
 *      when set to string run the function (this is solved a problem, but this is not a good solution, Uv)
 */
    function xmlreq_put(url,to_where, replace_content) {
		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;
		    }
		}

        if( (typeof replace_content =='boolean') &&(replace_content == true)) {
            var parent = jQuery('#'+to_where).parent();
            if( (parent.attr('id') == '') && (parent.attr('id') == undefined)) {
                parent.attr('id', 'randid'+Math.round(Math.random()*0xFFFF));
            }
            to_where = parent.attr('id');
        }
        var tw=jQuery('#'+to_where);
		var ch1=tw.height();
		var ch2=tw.width();

        // set ajax 'loading ....'
		tw.html('<table height="'+ch1+'" width="'+ch2+'"><tr><td valign="top" align="left"><img border="0" src="/ui2/images/loading.gif"> <b style="color:darkred;">'+tg("Loading...")+'</b></td></tr></table>');
        jQuery.get(url,function(respond){
            applyContentsImp(respond,to_where,replace_content);
        });
/*
		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(tg('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(tg('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);

    }
/**
 *
 * @param http_request
 * @param string where
 * @param function on_complete_func
 */
    function applyContents(http_request,where,on_complete_func) {
        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
                applyContentsImp(http_request.responseText, where,on_complete_func);
            } /*else {
                alert('There was a problem with the request.');
            }*/
        }
    }

/**
 *
 * @param string responseText http_request.responseText
 * @param string where url
 * @param function on_complete_func
 */
    function applyContentsImp(responseText,where,on_complete_func) {
        var dest = d(where) || {};
        //if (dest.nodeType) dest.innerHTML = http_request.responseText;
        if (dest.nodeType) {
            jQuery(dest).html(responseText); // support jQuery
        }
        if (typeof qtip_init =='function'){ // enable tooltips for ajax-generated content
            qtip_init();
        }
        if( typeof on_complete_func !='boolean') {
            if( typeof on_complete_func!='function') {
                eval(on_complete_func);
            } else {
                on_complete_func.call(dest,responseText);
            }
        }
    }



// 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(callback_function, question_text, question_value) {
    var buttons = {};
    buttons[tg('Ok')] = function(){ callback_function(jQuery(this).find('input[name="aep_text"]').val()); jQuery(this).dialog("close"); };
    buttons[tg('Cancel')] = function(){ callback_function(null); jQuery(this).dialog("close"); };
    var params = {
        buttons: buttons
    };
    jQuery('.aep_prompt').html(question_text);
    open_dialog(document.domain + ' question:', jQuery('#aep_w').html(), params);
    var $input = jQuery('#dialogbox').find('input[name="aep_text"]');
    $input.val(question_value);
    $input.focus();
    $input.select();
    ae_cb = callback_function;
    return;
}

// 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
    jQuery('#dialogbox').dialog('close');
	if (!m)
		ae_cb(null);  // user pressed cancel, call callback with null
	else
		ae_cb(jQuery('#dialogbox').find('input[name="aep_text"]').val()); // 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) {
    open_dialog(popup_title, popup_contents);
}

// 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
	jQuery('#dialogbox').dialog('close');
}




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

/**
 * setting up & open dialog -- used to use spop, now uses jQuery dialog
 * @param string popup_title
 * @param string req_url
 * @param object extra_params (optional)
 * @param function|string on_complete_func (optional)
 */
function open_in_popup (popup_title, req_url, extra_params, on_complete_func, container_obj) {
    jQuery.ajax({
        url: req_url,
        success: function(data) { open_dialog(popup_title, data, extra_params, on_complete_func, container_obj); qtip_init(); }
    });
}
/**
 * lower level function to open dialog -- called by all functions that use popup
 * @param string popup_title
 * @param string popup_text
 * @param object extra_params
 * @param string|function on_complete_func code to execute after the dialog has been displayed
 */
function open_dialog(popup_title, popup_text, extra_params, on_complete_func, container_obj) {
    if(typeof(extra_params)=='undefined') {
        extra_params = {};
    }
    if(typeof(container_obj)=='undefined') {
        container_obj = jQuery('#dialogbox');
    }
    extra_params.modal = true;
    extra_params.title = popup_title;
    container_obj.html(popup_text).dialog('destroy').dialog(extra_params).dialog('open');

    if (typeof(on_complete_func)=='function'){
        on_complete_func.call(container_obj,popup_text);
    } else if(typeof(on_complete_func)=='string') {
        eval(on_complete_func);
    }
    // solves centering issue on certain browsers, eg FF
    container_obj.dialog('option', 'position', 'center');
}
/**
 * closes dialog popup
 */
function close_popup() {
    jQuery('#dialogbox').dialog('close');
}

/**
 * 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){
        if(el.style)
		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 print_content(){
	window.print();
	return false;
}

function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getPageHeight() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }

  return (myHeight);
}


