var ASMImgButtons = new Array();
var preloader = new Image();
preloader.src = images+'/preloader.gif';
var bui = {
		overlayCSS: {backgroundColor:'#000', opacity: '0.1'},
		css: { backgroundColor: 'transparent',border:'none',padding:0,margin:0},
		baseZ:1000000,
		fadeOut:100,
		message:'<img src="'+images+'/preloader.gif" border=0>'
	};

//////////////////////////////////////////////
//			START SITE INITIALIZATION		//
//////////////////////////////////////////////
function localshow(obj) {
	if(typeof obj == 'string') {
		var ee = obj;
	} else {
		var ee = $(obj).attr('href');
	}
	$.get(ee, response);
	return false;
}
function ajaxLoadingStart() {
	$.blockUI(bui);
}
function ajaxLoadingStop() {
	$.unblockUI();
}
$.ajaxSetup({dataFilter:preprocessHTML});
$(document)
	.ajaxStart(ajaxLoadingStart)
	.ajaxStop(ajaxLoadingStop);

//////////////////////////////////////////////
//		END SITE INITIALIZATION				//
//////////////////////////////////////////////
function preprocessHTML(result, type) {
	if(result && typeof result == 'object') {
		var res = result.getElementsByTagName('asmResponse');
		if((!res) || (!res.length) || (res.length==0)) return result;
	} else return result;
	var err = result.getElementsByTagName('error');
	if(err && err.length && err[0].childNodes.length) showStatusMessage('error', err[0].childNodes[0].nodeValue );

	var warn = result.getElementsByTagName('warning');
	if(warn && warn.length && warn[0].childNodes.length) showStatusMessage('warning', warn[0].childNodes[0].nodeValue );

	var notice = result.getElementsByTagName('notice');
	if(notice && notice.length && notice[0].childNodes.length) showStatusMessage('notice', notice[0].childNodes[0].nodeValue );

	var resp = result.getElementsByTagName('response')[0].childNodes;
	var ret = '';
	for( var i=0; i<resp.length; i++) {
		ret += resp[i].nodeValue;
	}
	return ret;
}
jQuery.fn.extend({
	load: function( url, params, callback ) {
		if ( typeof url !== "string" )
			return this._load( url );
	
		var off = url.indexOf(" ");
		if ( off >= 0 ) {
			var selector = url.slice(off, url.length);
			url = url.slice(0, off);
		}
	
		// Default to a GET request
		var type = "GET";
	
		// If the second parameter was provided
		if ( params )
			// If it's a function
			if ( jQuery.isFunction( params ) ) {
				// We assume that it's the callback
				callback = params;
				params = null;
	
			// Otherwise, build a param string
			} else if( typeof params === "object" ) {
				params = jQuery.param( params );
				type = "POST";
			}
	
		var self = this;
	
		// Request the remote document
		jQuery.ajax({
			url: url,
			type: type,
			data: params,
			dataFilter:function(){},
			complete: function(res, status){
				// If successful, inject the HTML into all the matched elements
				if ( status == "success" || status == "notmodified" )
					if(res.responseXML && res.responseXML.documentElement) var resp = preprocessHTML(res.responseXML);
					else var resp = res.responseText;
					// See if a selector was specified
					self.html( selector ?
						// Create a dummy div to hold the results
						jQuery("<div/>")
							// inject the contents of the document in, removing the scripts
							// to avoid any 'Permission Denied' errors in IE
							.append(resp.replace(/<script(.|\s)*?\/script>/g, ""))
	
							// Locate the specified elements
							.find(selector) :
	
						// If not, just inject the full result
								resp );
	
				if( callback )
					self.each( callback, [resp, status, res] );
			}
		});
		return this;
	}
});

function detectLanguage() {
	languageinfo=navigator.language? navigator.language : navigator.userLanguage;
	return languageinfo.substr(0,2);
}

function findObj(theObj, theDoc) {
	var p, i, foundObj;
	if(!theDoc) theDoc = document;
	if( (p = theObj.indexOf("?")) > 0 && parent.frames.length) {
		theDoc = parent.frames[theObj.substring(p+1)].document;
		theObj = theObj.substring(0,p);
	}
	if(!(foundObj = theDoc[theObj]) && theDoc.all) foundObj = theDoc.all[theObj];
	for (i=0; !foundObj && i < theDoc.forms.length; i++)
		foundObj = theDoc.forms[i][theObj];
	for(i=0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++)
		foundObj = findObj(theObj,theDoc.layers[i].document);
	if(!foundObj && document.getElementById) foundObj = document.getElementById(theObj);
	return foundObj;
}

function getSelectValue(obj) {
	i=obj.selectedIndex;
	return obj.options[i].value;
}

function newImage(name, arg1, arg2) {
	ASMImgButtons[name] = new Array;
	ASMImgButtons[name][0] = new Image();
	ASMImgButtons[name][0].src = arg1;
	ASMImgButtons[name][1] = new Image();
	ASMImgButtons[name][1].src = arg2;
}

function changeImages(name, num, imgname) {
	if(!imgname) imgname=name;
	var img = findObj(imgname);
	img.src = ASMImgButtons[name][num].src;
	return true;
}

function IsNumeric(sText) {
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;

	for (i = 0; i < sText.length && IsNumber == true; i++) {
		Char = sText.charAt(i);
		if (ValidChars.indexOf(Char) == -1) IsNumber = false;
	}
	return IsNumber;

}

////////////////////////////////////////////////////////
//                  Favorites
////////////////////////////////////////////////////////
function bookmark(url, title){
	if (!url) url = location.href;
	if (!title) title = document.title;
	
	//Gecko
	if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function")) window.sidebar.addPanel (title, url, "");
	//IE4+
	else if (typeof window.external == "object") window.external.AddFavorite(url, title);
	//Opera7+
	else if (window.opera && document.createElement) {
		var a = document.createElement('a');
		if (!a) { //IF Opera 6
			alert("Press CTRL-T to bookmark this page.");
		}
		a.setAttribute('rel','sidebar');
		a.setAttribute('href',url);
		a.setAttribute('title',title);
		a.click();
	} else alert("Press CTRL-D to bookmark this page.");
	return false;
}
////////////////////////////////////////////////////////
//				Status messages
////////////////////////////////////////////////////////
var currentstatusmessagescount = 0;
function closeStatusMessage(autoclose, parent, div){
	if(typeof document.getElementById(div) != 'undefined'){
		if(document.getElementById(div).statusmessagenumber == currentstatusmessagescount){
			document.getElementById(parent).removeChild(document.getElementById(div));
			currentstatusmessagescount--;
			if(currentstatusmessagescount == 0){
				document.getElementById(parent).style.display = 'none';
			}
		}else{
			setTimeout("closeStatusMessage('"+autoclose+"','"+parent+"','"+div+"')", parseInt(autoclose)*1000);
		}
	}
}
function cleanStatusMessages(parent){
	if(typeof parent == 'undefined'){
		parent = 'statusmessagebox';
	}
	document.getElementById(parent).innerHTML = '';
	currentstatusmessagescount = 0;
}
function showStatusMessage(type, msg, autoclose, parent, callback){
	if(typeof parent == 'undefined'){
		parent = 'statusmessagebox';
	}
	div = document.createElement('div');
	ts = new Date().getTime();
	div.id = 'statusDiv'+ts;
	div.statusmessagenumber = ++currentstatusmessagescount;

	div.innerHTML = msg;
	switch(type) {
	case 'error':
		div.title = 'Error';
		var iconname = 'closethick';
		var iconclass = 'error';
		break;
	case 'warning':
		div.title = 'Warning';
		var iconname = 'alert';
		var iconclass = 'error';
		break;
	case 'notice':
		div.title = 'Notice';
		var iconname = 'info';
		var iconclass = 'highlight';
		break;
	default:
		div.title = 'Information';
		var iconname = 'check';
		var iconclass = 'highlight';
	}
	document.body.appendChild(div);
	$('div#'+div.id).prepend($('<div class="ui-icon ui-icon-'+iconname+'" style="float:left; margin:0 7px 20px 0;"></div>'));
	if(document.getElementById('videoplayer')){
		document.getElementById('videoplayer').style.visibility='hidden';
	}
	$('#'+div.id).dialog({
		'modal':true,
		'height':'auto',
		'width':$.browser.msie?400:'auto',
		'stack':true,
		'bgiframe':true,
		'overlay':{'opacity':0.3, 'background':'black'},
		'dialogClass':'ui-state-'+iconclass,
		'buttons':{
			'Close':function() {
				$(this).dialog('destroy');
				$(this).remove();//some kind of a HOOK, cause modal dialogs aren't greedy enough with element focus
			}
		},
		close: function(){
			if(document.getElementById('videoplayer')){
				document.getElementById('videoplayer').style.visibility='visible';
			}
			$(this).dialog('destroy');
			$(this).remove();//some kind of a HOOK, cause modal dialogs aren't greedy enough with element focus
		}
	});
	if(typeof callback != 'undefined') {
		$('#'+div.id).dialog('option', 'close', callback);

	}
}
////////////////////////////////////////////////////////
//                  Display errors
////////////////////////////////////////////////////////
function ASMShowErrors(result) {
	checkErrors=true;
	cleanStatusMessages();
	if(typeof result != 'object')  return false;
	var errxml = result.getElementsByTagName('ASMErrors').item(0).childNodes;
	var errors = '';
	var warnings = '';
	var notices = '';
	for(var i=0; i<errxml.length; i++) {
		var res = errxml.item(i);
		var t = new ASMErrorMessage(res.tagName, res.childNodes[0].nodeValue, res.getAttribute('url'), res.getAttribute('description'), res.getAttribute('file'), res.getAttribute('line'), res.getAttribute('class'), res.getAttribute('method'), res.getAttribute('function'));
		eval('document.' + res.tagName + 's += ASMBuildError(t) + "<br>";');
	}
	if(errors.length>0) showStatusMessage('error', errors);
	if(warnings.length>0) showStatusMessage('warning', warnings);
	if(notices.length>0) showStatusMessage('notice', notices);
}

function ASMErrorMessage(type, message, url, description, efile, eline, eclass, emethod, efunction) {
	this.addtime= new Date();
	this.type=type;
	this.message=message;
	this.url=url || false;
	this.description=description || false;
	this.efile=efile || false;
	this.eline=eline || false;
	this.eclass=eclass || false;
	this.emethod=emethod || false;
	this.efunction=efunction || false;
}

function ASMBuildError(error) {
	var str='';
	var posstr='';
	str += ' ' + error.message.bold();
	if(error.description) str += ' ( ' + error.description + ' )';
	if(posstr.length>0) str += '<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[' + posstr.italics() + ']';

	return str;
}
////////////////////////////////////////////////////////
//				End of Display errors
////////////////////////////////////////////////////////
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}
function refresh(){
	if(window.navigate){
		window.navigate(window.location.href);
	}else{
		window.location.reload(true);
	}
}

function cartitem(id, price, cnt) {
	var id = id;
	var price = price;
	var count = cnt?cnt:1;
	
	
	this.setCount = function(cnt) {
		cnt = parseInt(cnt);
		this.count = cnt;
	};
	
	this.getTotalPrice = function() {
		return price * count;
	};
	
	this.getID = function() {return id;};

	this.getPrice = function() {return price;};

	this.getCount = function() {return count;};
	this.setCount = function(cnt) {count = parseInt(cnt);};
}

var cart = new function() {
	var items = [];
	
	this.haveItem = function(id) {
		var item = getItem(id);
		if(!item) return false;
		return true;
	};
	
	this.add = function(id, price, cnt) {
		cnt = parseInt(cnt);
		if(cnt==0) cnt=1;
		items[items.length] = new cartitem(id, price, cnt);
		save();
	};
	
	this.setCount = function(id, cnt) {
		var item = getItem(id);
		if(!item) return null;
		item.setCount(cnt);
		save();
	};

	this.getCount = function(id) {
		var item = getItem(id);
		if(!item) return null;
		return item.getCount();
	};
	
	this.getPrice = function(id) {
		var item = getItem(id);
		if(!item) return null;
		return item.getPrice();		
	};
	
	this.getTotalPrice = function(id, fxd) {
		var price = 0.0;
		if(!fxd) fxd=2;
		if(!id) {
			for(var i=0; i<items.length; i++) {
				price += items[i].getTotalPrice();
			}
		} else {
			var item = getItem(id);
			if(item) {
				price = item.getTotalPrice();
			}
		}
		return price.toFixed(fxd);
	};
	
	var getItem = function(id) {
		for(var i=0; i<items.length; i++) {
			if(items[i].getID() == id) {
				return items[i];
			}
		}
	};
	
	this.getInfo = function(id, name) {
		var item = getItem(id);
		if(!item) return null;
		return item.getName();
	};
	
	var setCookie = function(name, value) {
	      var valueEscaped = escape(value);
	      var expiresDate = new Date();
	      expiresDate.setTime(expiresDate.getTime() + 365 * 24 * 60 * 60 * 1000);
	      var expires = expiresDate.toGMTString();
	      var newCookie = name + "=" + valueEscaped + "; path=/; expires=" + expires;
	      if (valueEscaped.length <= 4000) document.cookie = newCookie + ";";
	      else return false;
	      return true;
	};
	
	var getCookie = function(name) {
		var cookie = " " + document.cookie;
		var search = " " + name + "=";
		var setStr = null;
		var offset = 0;
		var end = 0;
		if (cookie.length > 0) {
			offset = cookie.indexOf(search);
			if (offset != -1) {
				offset += search.length;
				end = cookie.indexOf(";", offset);
				if (end == -1) {
					end = cookie.length;
				}
				setStr = unescape(cookie.substring(offset, end));
			}
		}
		return(setStr);
	};

	this.load = function() {
		var data = getCookie("cart");
		if(!data) return;
		data = data.split(';');
		for(var i=0; i<data.length; i++) {
			v = data[i].split(':');
			this.add(v[0], v[1], v[2]) ;
		}
	};

	var save = function() {
		var data=[];
		for(var i=0; i<items.length; i++) {
			data[data.length] = [items[i].getID(), items[i].getPrice(), items[i].getCount()].join(":");
		}
		data = data.join(';');
		return setCookie('cart', data);
	};

	this.load();
};
