function win_x()
{
	var v;
	v=window.innerWidth;
	if (!v) v=document.body.clientWidth;
	return 1*v;
}

function win_y()
{
	var v;
	v=window.innerHeight;
	if (!v) v=document.body.clientHeight;
	return 1*v;
}

var popup_layer_generators={
	".progress": "<div class='#divclass#' style='position: absolute; display: none; padding: 10px; width: 210px; height: 30px;background-color: #ffffff;z-index:20;'><img src='/shared/progress.gif'/></div>",
	".window-shadow": "<div class='#divclass#' style='position: absolute; display: none; width: 100%; height: 100%; left: 0px; top: 0px; filter: alpha(opacity=30); opacity: 0.3; -moz-opacity:0.3; background-color: #ffffff;z-index:3;'></div>"
};

function generate_popup_layers(divid)
{
	if ($(divid).length) return;
	var divclass=divid.replace(/^\./,"");
	if (popup_layer_generators[divid]) {
		var r;
		if (typeof popup_layer_generators[divid]=="string") {
			var str=popup_layer_generators[divid].replace(/#divclass#/g,divclass);
			r=$(str).appendTo($("body"));
		}
		if (popup_layer_generators[divid+"::after"]) popup_layer_generators[divid+"::after"](r);
	}
}

function popup_show(divid,shadow,mode)
{
	var d=$(divid).css("display");
	generate_popup_layers(divid);
	if (shadow) generate_popup_layers(".window-shadow");
	if (mode==undefined) {
		if (d=="block") mode=0; else mode=1;
	}
	if (mode==0) {
		$(divid).css("display","none");
		if (shadow) $(".window-shadow").css("display","none");
		return;
	}
	if (shadow) $(".window-shadow").css("display","block");
	$(divid).css("display","block");
	$(divid).css("position","absolute");
	$(divid).css("top", (($(window).height() - $(divid).outerHeight()) / 2) + $(window).scrollTop() + "px");
	$(divid).css("left", (($(window).width() - $(divid).outerWidth()) / 2) + $(window).scrollLeft() + "px");
}

function ajaj_form(frm,callback_func)
{
	var params={ajaj:1};
	var i;
	var t;
	var v;
	var tmp;
	for(i=0;i<frm.length;i++) {
		t=frm.elements[i].type;
		var el=frm.elements[i];
		switch (t) {
			case 'hidden':
			case 'text':
			case 'password':
			case 'textarea':
				if (!frm.vis) {
					v=el.value;
				} else if (frm.vis.value.indexOf(","+el.name+",")!=-1) {
					v=tinyMCE.get(el.name).getContent();
				} else {
					v=el.value;
				}
				params[el.name]=v;
				break;
			case 'checkbox':
				if (el.checked) params[el.name]=el.value;
				break;
			case 'select':
			case 'select-one':
				params[el.name]=el.options[el.selectedIndex].value;
				break;
			case 'radio':
				/*tmp=get_radio_value(el);
				if (tmp.length) {
					params+="&";
					params+=escape(el.name);
					params+="=";
					params+=escape2(tmp);
				}*/
				break;
			case 'button':
			case 'submit':
				break;
			default:
			alert("Unknown type "+t);
		}
	}
/*	std_response(*/
	$.ajax({
		type: "POST",
		url: frm.action,
		data: params,
//		async: false,
		success: function(a) {std_response(a,callback_func);}
	})/*.responseText
	)*/;
}

function ajaj_href(href,callback_func)
{
	if (href.href) href=href.href;
	$.ajax({
		type: "GET",
		url: href,
		success: function(a) {std_response(a,callback_func);}
	});
}

function init_lightbox(path)
{
	$(path).lightBox({
		fixedNavigation:true,
		imageLoading:  '/shared/jquery_lightbox/images/lightbox-ico-loading.gif',
		imageBtnClose: '/shared/jquery_lightbox/images/lightbox-btn-close.gif',
		imageBtnPrev:  '/shared/jquery_lightbox/images/lightbox-btn-prev.gif',
		imageBtnNext:  '/shared/jquery_lightbox/images/lightbox-btn-next.gif',
		imageBlank:    '/shared/jquery_lightbox/images/lightbox-blank.gif'
	});
}

function init_tabs(path_names,path_tabs)
{
	var clicker=function(e,a) {
		if (!a) a=this;
		var act=a.href.replace(/^.*#/,'');
		$(path_tabs).each(function(i) {
			if (act==this.id) $(this).show(); else $(this).hide();
		});
		$(path_names).each(function(i) {
			if (this==a) $(this).addClass("A"); else $(this).removeClass("A");
		});
	};
	$(path_names).bind("click",clicker);
	var tabsel;
	var arr;
	if (arr=document.location.toString().match(/#(.*)$/)) {
		$(path_names).each(function(i) {
			var act=this.href.replace(/^.*#/,'');
			if (act==arr[1]) tabsel=this;
		});
	}
	if (!tabsel) {
		tabsel=$(path_names)[0];
	}
	clicker({},tabsel);
}

function add_to_cart(action,id,amount)
{
	if (!id) return;
	if (id=="") return;
	popup_show(".progress",1,1);
	$.ajax({
		type: "POST",
		url: action,
		data: {ajaj:1,mode:"add_to_cart",item_id:id,amount:amount},
		success: function (r) {
			popup_show(".progress",1,0);
			std_response(r);
		},
		error: function(r) {
			popup_show(".progress",1,0);
		}
	});
}

function gallery_easy_init(src,dst,preview)
{
	$(src).bind("click",function() {gallery_easy_press(src,dst,preview,this);});
	var flag=true;
	if (document.location.hash) {
		var h=document.location.hash.toString().replace(/#/,'');
		var arr=$(src);
		for (var i=0;i<arr.length;i++) {
			if ($(arr[i]).attr("id")==h) {
				flag=false;
				gallery_easy_press(src,dst,preview,arr[i]);
			}
		}
	}
	if (flag) gallery_easy_press(src,dst,preview,$(src)[0]);
}

function gallery_easy_press(src,dst,preview,img)
{
	var url=$(img).attr("src");
	$(dst).attr("src",url.replace(/-preview\d+\w*/,preview));
	document.location.hash=$(img).attr("id");
}

function set_select(list,pid) {
	var i=0;
	var j=1;
	while (list.options[i] && j) {
		if (list.options[i].value==pid) {
			list.selectedIndex=i;
			j=0;
		}
		i++;
	}
}

function set_radio(list,pid)
{
	if (!list.length) list=[list];
	for (var i=0;i<list.length;i++) {
		if (list[i].value==pid) list[i].checked=true;
	}
}

function set_checked(list,rule)
{
//	if (list.constructor!=Array) list=[list];
	if (rule==1 || rule==0) {
		var i=0;
		while (list[i]) {
			list[i].checked=rule==1?true:false;
			i++;
		}
		return;
	}
	var i=0;
	var h={};
	if (rule.constructor==Array) {
		for (var j=0;j<rule.length;j++) h[rule[j]]=1;
	} else {
		h[rule]=1;
	}
	while (list[i]) {
		list[i].checked=(h[list[i].value])?true:false;
		i++;
	}
}

function owcms_hslider(options)
{
	var hpw=options.handle.width();
	var iw=0;
	var items=$(".item",options.items);
	for (var i=0;i<items.length;i++) {
		iw+=$(items[i]).width();
	}
//	alert("ow="+iw+", hpw="+hpw);
	if (iw>hpw) {
		var hw=Math.floor(hpw*hpw/iw);
		$(".handle",options.handle).css({width:hw});
	}

}

function owcms_slider(options)
{
	if (options.slides.length<2) return;
	setTimeout(function() {owcms_slider_slide_to(options,1);},8000,1);
	if (options.marks) {
		for (var i=0;i<options.marks.length;i++) {
			$(options.marks[i]).bind("click",{i:i}, function(e) {options.stop=1;owcms_slider_slide_to(options,e.data.i);});
		}
	}
}

function owcms_slider_slide_to(options,n,auto)
{
	if (options.stop && auto) return;
	var i=n;
	options.slides.stop().animate({opacity:0},{complete: function() {
		options.slides.hide();
		$(options.slides[i]).css({opacity: 0}).show().animate({opacity:1});
		if (options.marks) {
			options.marks.removeClass("markA");
			$(options.marks[i]).addClass("markA");
		}
	}});
	n++;
	if (n>=options.slides.length) n=0;
	setTimeout(function() {owcms_slider_slide_to(options,n,1);},7000);
}

var _img_rot;
function img_rot()
{
	if (!_img_rot) {_img_rot=new Image();_img_rot.src="/shared/progress-rot.gif";}
	return _img_rot.src;
}

function img_bigger_preview(img,size,offsetLeft,offsetTop)
{
	var previewer=$("#imgbiggerpreview");
	if (previewer.length==0) {
		previewer=$("<img src='/shared/empty.gif' id='imgbiggerpreview' style='display: none;position: absolute;border: 1px solid #808080;'/>").appendTo($("body"));
	}
	if (size==undefined) {
		previewer.hide();
		return;
	}
	var o=$(img).offset();
	previewer.css({
		top: o.top+(offsetTop||20),
		left: o.left+(offsetLeft||20)
	});
	previewer.attr("src",img_rot());
	previewer.show();
	previewer.attr("src",$(img).attr("src").replace(/-preview\d+\w*/,"-preview"+size));
}

function mkpreview(url,mode)
{
	if (!url) return "/shared/empty.gif";
	url=url.replace(/-preview\d+\w*/,"");
	return url.replace(/(\.\w+)$/,"-preview"+mode+"$1");
}

/*
	Inits for standart form:
		1. inputs can have 'alt' attr, it that is the case, then value=alt is done on start
		2. class 'default' css class is added to all inputs & textareas
		3. on focus:
			3.1 'default' css class is removed as 'active' is added
			3.2 if input has 'alt' attr and it is equal to 'value' attr, value==""
		4. on blur:
			4.1 'active' css class is removed
			4.2 if input 'value' attr is empty, then 'default' css class added
			4.3 if input 'value' attr is empty and input has 'alt' attr, then value=alt

*/
function generic_site_form_init(path)
{
	var inputs=$(path+" .field input");
	for (var i=0;i<inputs.length;i++) {
		var a=$(inputs[i]).attr("alt");
		if (a) $(inputs[i]).attr("value",a);
	}
	$(path+" input, "+path+" textarea").addClass("default").bind("focus",function() {
		$(this).removeClass("default").addClass("active");
		if ($(this).attr("alt") && $(this).attr("alt")==$(this).attr("value")) $(this).attr("value","");
	}).bind("blur",function() {
		$(this).removeClass("active");
		if ($(this).attr("value")=="") {
			$(this).addClass("default");
			if ($(this).attr("alt")) $(this).attr("value",$(this).attr("alt"));
		}
	});
}

/*
	Checks standart form:
	

	Returns:
		is form is okay, then true
*/
function generic_site_form_check(path)
{
	var flag=true;
	var must=$(path+" .field.must input ,"+path+" .field.must select, "+path+" .field.must textarea");
	for (var i=0;i<must.length;i++) {
		var inp=must[i];
		var err;
		var inptype=inp.type;
		switch (inptype) {
			case "text":
			case "textarea":
				if (inp.value=="") err="empty";
				if (inp.alt && inp.alt==inp.value) err="empty";
				break;
			case "select":
				if (inp.options[inp.selectedIndex].value=="") err="empty";
				break;
			default:
				alert("Unknown field type - "+inptype);
		}
		var fieldnode=inp.parentNode.parentNode;//TODO
		if (err) {
			flag=false;
			$(" .err",fieldnode).text("Заполните, пожалуйста, поле");
		} else {
			$(" .err",fieldnode).text("");
		}
	}
	return flag;
}


function Dumper(obj, indent,findent) {
	if (!indent) indent="";
	if (!findent) findent="";
	if (indent.length>4) return findent+"...\n";
	if (obj==null) return findent+"null\n";
	if (obj==undefined) return findent+"undefined\n";
	switch (typeof obj) {
		case "string":
			return findent+'"'+obj+'"\n';
		case "number":
		case "boolean":
			return findent+obj+'\n';
		case "object":
			if (obj.constructor==Array) {
				var ret=findent+" [\n";
				for (var i=0;i<obj.length;i++) {
					ret+=Dumper(obj[i],indent+"\t",indent+"\t");
				}
				ret+=indent+"]\n";
				return ret;
			} else {
				ret=findent+"{\n";
				for (var item in obj) {
					if (item.charAt(0)=='_') continue;
					ret+=indent+"\t"+item+": "+Dumper(obj[item],indent+"\t","");
				}
				ret+=indent+"}\n";
				return ret;
			}
			break;
		default:
			return findent+(typeof obj)+'\n';
	}

}

function Clone(obj)
{
	if (!obj) return obj;
	if(typeof obj!='object') return obj;
	var ret;
	if (obj.constructor==Array) {
		ret=[];
		for (var i=0;i<obj.length;i++) ret.push(Clone(obj[i]));
	} else {
		ret={};
		for (var k in obj) ret[k]=(Clone(obj[k]));
	}
	return ret;
}


function std_response(rtext,callback_func)
{
	var ret;
	if (typeof rtext == "string") {
		try {
			eval("ret="+rtext+";");
		} catch(e) {
			if (!rtext.match(/<br\s*\/?>/i)) rtext=rtext.replace(/\n/g,'<br/>');
			var d=$('<div><div style="text-overflow: auto; max-height: 500px;"></div></div>');
			d.attr('title',"Internal server error");
			$("div",d).html(rtext);
			d.appendTo($('body'));
			d.dialog({maxHeight: 550,close: function() { d.dialog("destroy");d.remove(); }});
			return undefined;
		}
	} else {
		ret=rtext;
	}
	if (ret.error_code) {
		if (!ret.error.match(/<br\s*\/?>/i)) ret.error=ret.error.replace(/\n/g,'<br/>');
		var d=$('<div><div style="text-overflow: auto; max-height: 500px;"></div></div>');
		d.attr('title',ret.error_title);
		$("div",d).html(ret.error);
		d.appendTo($('body'));
		d.dialog({maxHeight: 550,close: function() { d.dialog("destroy");d.remove(); }});
	} else if (ret.redirect) {
		document.location=ret.redirect.url;
	} else if (ret.refresh) {
		if (document.location.search && document.location.search=="?do-logoff=1") {
			document.location.search="";
		} else {
			document.location.reload();
		}
	} else if (ret.call) {
		eval(ret.call+'(ret)');
	} else if (callback_func) {
		callback_func(ret);
	}
	return ret;
}

/*
	params: hash of:
	params.previews_click_path - jquery path
	params.previews_image_subpath - jquery path, can be empty
	params.big_image_path - jquery path
	params.progress - defaults to /shared/progress-rot.gif
	params.full_path
	params.change_effect - function(div_preview,div_big,on_complete) {}
	params.preview_select - function(element)
	params.preview_mouseover - function(element)
	params.preview_mouseout - function(element)
	params.preview_deselect - function(element)
	params.size
	params.preview_active_class - defaults to 'itemA'
	params.preview_hover_class - defaults to 'itemH'
	
*/
function owcms_gallery(params)
{
	this.params=params;
	var t=this;
	if (!this.params.progress) this.params.progress='/shared/progress-rot.gif';
	if (!this.params.change_effect) this.params.change_effect=function(p) {
		$(t.params.big_image_path).animate({opacity:0},{complete: function() {
			p.on_complete();
			$(t.params.big_image_path).animate({opacity:1});
		}});
	};
	if (!this.params.preview_active_class) this.params.preview_active_class='itemA';
	if (!this.params.preview_hover_class) this.params.preview_hover_class='itemH';
	this.params.big_is_img=$(this.params.big_image_path)[0].tagName=='IMG';
	this.params._progress=new Image();
	this.params._progress.src=this.params.progress;
	this.selected=this.from_hash();
	this.init();
}

owcms_gallery.prototype.init=function() {
	var t=this;
	var arr=$(this.params.previews_click_path);
	this.cnt=arr.length;
	for (var i=0;i<arr.length;i++) {
		$(arr[i]).bind("click",{i:i},function(e) {t.select(e.data.i);});
	}
	arr.bind("mouseover",function(){ $(this).stop().addClass(t.params.preview_hover_class,200); });
	arr.bind("mouseout",function(){ $(this).stop().removeClass(t.params.preview_hover_class,200); });
	this.select(this.selected);
}

owcms_gallery.prototype.select=function(i) {
//	alert("select i="+i);
//	if (i==this.selected) return;
	this.set_hash(i);
	this.selected=i;
	var t=this;

	var newimg;
	var d=$(this.params.previews_click_path)[i];
	if (this.params.previews_image_subpath) d=$(this.params.previews_image_subpath,d)[0];
	if (d.tagName=="IMG") {
		newimg=d.src;
	} else {
		newimg=$(d).css("background-image").replace(/^url\("?/,"").replace(/"?\)/,"");
	}
	newimg=mkpreview(newimg,this.params.size);
	$(this.params.previews_click_path).removeClass(this.params.preview_active_class);
	function oncompl() {
		if (t.params.big_is_img) {
			$(t.params.big_image_path).attr("src",t.params.progress);
			setTimeout(function() { $(t.params.big_image_path).attr("src",newimg); },1);
		} else {
			$(t.params.big_image_path).css({"background-image":"url("+t.params.progress+")"});
			setTimeout(function() { $(t.params.big_image_path).css({"background-image":"url("+newimg+")"}); },1);
		}
	}
	$($(this.params.previews_click_path)[i]).addClass(this.params.preview_active_class);
	this.params.change_effect({i:i,on_complete:oncompl});
}

owcms_gallery.prototype.next=function() {
	if (this.selected+1!=this.cnt) this.select(this.selected+1); else this.select(0);
}

owcms_gallery.prototype.prev=function() {
	if (this.selected!=0) this.select(this.selected-1); else this.select(this.cnt-1);
}

owcms_gallery.prototype.set_hash=function(i) {
	document.location.hash="img"+i;
}

owcms_gallery.prototype.from_hash=function() {
	if (!document.location.hash) return 0;
	var h=document.location.hash.toString().replace(/#/,'').replace(/img/,'');
	return h*1;
}

function Views()
{
	this.c={};
	this.globalspace={functions:{},controllers:{}};
	this.process=function(name,space) {
		return this.c[name](this.globalspace,space);
	};
}

var views=new Views();


