jQuery.fn.extend({
  serializeObject: function() {
    var obj = {};
    
    jQuery(this).find('input:text,input:password,:radio:checked,input:hidden,textarea,select')
    .each(function(){
    	obj[jQuery(this).attr('name')]= jQuery(this).val();
    });
    
    jQuery(this).find(':checkbox')
    .each(function(){
    	obj[jQuery(this).attr('name')]= (jQuery(this).attr('checked')?1:0);
    });
    
    return obj;
  },
  lock: function() {
  	var loader = typeof(arguments[0])=='undefined'? true: arguments[0];
  	//$(this).each(function(){
	   	var p_l = parseInt($(this).css('padding-left'));		p_l=isNaN(p_l)?0:p_l;
		var p_t = parseInt($(this).css('padding-top'));			p_t=isNaN(p_t)?0:p_l;
		var p_b = parseInt($(this).css('padding-bottom'));		p_b=isNaN(p_b)?0:p_l;
		var p_r = parseInt($(this).css('padding-right'));		p_r=isNaN(p_r)?0:p_l;
	   // Element border
		var b_l = parseInt($(this).css('border-left-width'));   b_l=isNaN(b_l)?0:b_l;
		var b_t = parseInt($(this).css('border-top-width'));	b_t=isNaN(b_t)?0:b_l;
		var b_b = parseInt($(this).css('border-bottom-width')); b_b=isNaN(b_b)?0:b_l;
		var b_r = parseInt($(this).css('border-right-width'));  b_r=isNaN(b_r)?0:b_l;
	   // Element offset
		var offset = $(this).offset();
	   // Element size and position
		var h = $(this).height() + p_t + p_b + b_t + b_b;
		var w = $(this).width() + p_l + p_r + b_l + b_r;
		var t = offset.top;
		var l = offset.left;
		var style = (h>40 && w>40 && loader)? 'style="background-image: url(/media/111/img/ajax-loader.gif);"':'';
		
		window.setInterval('$(".ajax_loader button").click(function(){unlock();}).show()',2000);
		$('<div class="ajax_loader" '+ style +'>' +
				'<div class="alc mt2">' +
				'<button class="hidden">'+ __('cancel') +'</buttom>' +
				'</div>' +
			'</div>').css({
			width: w,
			height: h,
			top: t,
			left: l
		}).appendTo('body');
  	//});
  },
  tooltip: function() {			
	var t = parseInt($(this).offset().top);
	var l = parseInt($(this).offset().left);
	
	var text = typeof arguments[0]!=='undefined'? arguments[0]:'';
	
	var tooltip = $('<div class="bubble hidden">' +
						'<div class="content"></div>'+
						text +
						'<img class="stem" src="/img/bubble/stem_tr.png">'+
					'</div>').appendTo('body');
	
	tooltip
		.css({
		  'top':t-6,
		  'left':(l-tooltip.width()-40)
		})
		.show();
	
	$(this).bind('mouseout',function(){tooltip.remove();});
  },
  sendData: function(){
  	var data = jQuery(this).serializeObject();
  	if(typeof(arguments[0])!=='undefined'){
  		data.url = arguments[0];
  	}
  	if(typeof(arguments[1])!=='undefined'){
  		data.lock = arguments[1];
  	}
  	ajax(data);
  }
});

function ajax(json){
	if(typeof(json)=='string'){
		json = JSON.parse(json);
	}
	$('.error_msg').hide();
	if(json.lock){
		$(json.lock).lock();
	}
	$.post(
		json.url,
		json,
		function(response){
			var output = JSON.parse(response);
			for(var i in output){
				ResponseHandler[output[i].action](output[i]);
			}
			unlock();
		}
	);  
} 
var ResponseHandler = {
	addClass:	function(resp){$(resp.p1).addClass(resp.p2);}, 
	after:		function(resp){$(resp.p1).after(resp.p2);},
	append:		function(resp){$(resp.p2 != null? resp.p2:'body').append(resp.p1);},
	attr:		function(resp){var a=resp.p1.split('|');$(a[0]).attr(a[1],resp.p2);},
	click:		function(resp){$(resp.p1).click();},
	css:		function(resp){var a=resp.p1.split('|');$(a[0]).css(a[1],resp.p2);},
	disable:	function(resp){$(resp.p1).attr('disabled',1);},
	empty:		function(resp){$(resp.p1).empty();},
	enable:		function(resp){$(resp.p1).removeAttr('disabled');},
	error:		function(resp){alert(resp.p1);},
	alert:		function(resp){alert(resp.p1);},
//	error:		function(resp){show_confirmation(resp.p1);}, // FIXME this should be default instead of alert()
	execute:	function(resp){window[resp.p1](resp.p2);},
	fadeout: 	function(resp){$(resp.p1).fadeOut('fast',function(){
					if(resp.p2!=null){
						var actions = resp.p2.split(',');
						for(var i in actions){
							try{
								ResponseHandler[actions[i]](resp);
							}catch(e){
								eval(actions[i]);
							}
						}
					}
				});},
	flash:		function(resp){
					var color = $(resp.p1).css('background-color');
					$(resp.p1).css('background-color',resp.p2).animate({'background-color':color});
				},
	hide:		function(resp){$(resp.p1).hide(resp.p2 || '');},
	html:		function(resp){$(resp.p1).html(resp.p2);},
	inlineError:function(resp){$('.error_msg',resp.p1).html(resp.p2).show();},
	load:		function(resp){$(resp.p1).load(resp.p2);},
	ok:			function(resp){show_confirmation(resp.p1);},
	redirect:	function(resp){window.location.href = resp.p1;},
	reload:		function(resp){location.reload();},
	remove:		function(resp){$(resp.p1).remove();},
	removeClass:function(resp){$(resp.p1).removeClass(resp.p2);},
	replace:	function(resp){$(resp.p1).replaceWith(resp.p2);},
	show:		function(resp){$(resp.p1).show(resp.p2 || '');},
	showText:	function(resp){$(resp.p1).show().text(resp.p2 || '');},
	submit:		function(resp){$(resp.p1).submit();},
	tb_remove:	function(resp){window.top.tb_remove();},
	test:		function(resp){document.getElementById('content').innerHTML=resp.p2;},
	toggleClass:function(resp){$(resp.p1).toggleClass(resp.p2);}, 
	val:		function(resp){$(resp.p1).val(resp.p2);},
	unbind:		function(resp){$(resp.p1).unbind(resp.p2);}
};

var ptUI = {
	UIcontainer: "", 
		
	init:  function(){
		if(typeof arguments[0] !== 'undefined' && $.isArray(arguments[0])){
			for (var i in arguments[0]){
				if(typeof this[arguments[0][i]] !== 'undefined'){
					if(arguments[0][i]==='init') continue;
					this[arguments[0][i]];
				}
			}
		}else{
			for (var i in this){
				if(i==='init' || i==='UIcontainer') continue;
				this[i]();
			}
		}
	},

	initHover: function(){
	   	$(".hover_el",this.UIcontainer)
		.mouseover(function (){$(this).addClass("hover");})
		.mouseout(function (){$(this).removeClass("hover");});
	},
	
	initRating: function(){
		// rating
			$('ul.rt_input li',this.UIcontainer)
			.bind('mouseover',function(){
				$(this)
					.prevAll().andSelf().addClass('act').end().end().nextAll().removeClass('act');
			})
			.bind('mouseout', function(){
				var val = $(this).parent().parent().find('input').val();
				$(this).siblings().andSelf().removeClass('act');
				$(this).parent().find('li:lt('+val+')').addClass('act');
			})
			.bind('click', function(){
				$(this).parent().parent().find('input').val($('ul.rating li').index(this)+1);
			});
	},
	
	initDefaultValues: function(){
		// Default values
		$('input[def],textarea[def]',this.UIcontainer)
			.each (function(){if($(this).val()=='' || $(this).val()==$(this).attr('def')){$(this).addClass('def_val').val($(this).attr('def'));}else{$(this).removeClass('def_val');}})
			.focus(function(){if($(this).val()==$(this).attr('def')){$(this).val('').removeClass('def_val');}})
			.blur (function(){if($(this).val()==''){$(this).addClass('def_val').val($(this).attr('def'));}});
	},	
	initMaxLength: function(){	
		// maxlength for textarea
		$('textarea[maxlength]',this.UIcontainer).keyup(function(){
			var max = parseInt($(this).attr('maxlength'));
			var len = $(this).val().length;
			if(len > max){
				$(this).val($(this).val().substr(0, $(this).attr('maxlength')));
			}
			$(this).parent().find('.charsRemaining').html(__("You have {n} characters remaining.").replace("{n}", max-len));
		});
	},
	initValueFilters: function(){
		// only allow integers
		$("input.integer",this.UIcontainer).keypress(function(e){
			  if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)){
				$(':animated').remove();
				$(this).after('<span class="warning">'+ __('Integers only') +'</span>').next().show().fadeOut("slow", function(){$(this).remove();});
			    return false;
		      }
		});
		// only allow decimals
		$("input.decimal",this.UIcontainer).keypress(function(e){
			  $(this).val($(this).val().replace(',', '.'));
			  if(e.which!=8 && e.which!=0 && (e.which<48 || e.which>57) && e.which!=44 && e.which!=46 || ($(this).val().indexOf('.')!=-1 && (e.which==44 || e.which==46))){
				$(':animated').remove();
				$(this).after('<span class="warning">'+ __('Decimal numbers only') +'</span>').next().show().fadeOut("slow", function(){$(this).remove();});
			    return false;
		      }
		});
	},
	initFormElements: function(){
		// combo
		$('.combo',this.UIcontainer)
			.click(function(e){
				$('.combo').not($(this)).find('.combo_slct').hide();
				if(e.target.className.search(/\bcombo|combo_value\b/) > -1){
					var slct = $(this).find('.combo_slct');
					slct.css('display', (slct.css('display')=='none'?'block':'none') );
				}
			})
			.find('select').bind('change',function(){
				var this_ = $(this);
				var selected = $('#o_'+this_.val(),this_);
				this_.next('.combo_value').html(selected.attr('short'));
			}).end()
			.find("a.closeBubble").click(function(){
				$(this).parent().parent().hide();
				return false;
			});
		
		// check boxes
		$('.check',this.UIcontainer)
		.click(function(){
			$(this).toggleClass('chk_on')
				.find('input')
					.attr('checked', !$(this).find('input').attr("checked"))
				.change();
		});
		
		// switcher
		$('.switcher .up',this.UIcontainer).click(function(){
			var val = parseInt($(this).parent().find('input').val())+1;
			var min = $(this).parent().attr('min');
			if(val<min){
				val = min;
			}	
			$(this).parent().find('input').val(val);
			$(this).parent().find('input').change();
		});
		$('.switcher .down',this.UIcontainer).click(function(){
			var val = parseInt($(this).parent().find('input').val())-1;
			var min = $(this).parent().attr('min');
			if(val<min){
				val = min;
			}	
			$(this).parent().find('input').val(val);
			$(this).parent().find('input').change();
		});
	},
	
	initHelp: function(){
		// Help
		$('input[help],textarea[help]',this.UIcontainer).each(function(){
				$(this)
				.bind('focus',function(){
					var elem = $(this);
					var offset = elem.offset();
					var t = parseInt(offset.top);
					var l = parseInt(offset.left);
					var w = elem.width();
					
					$('#'+elem.attr('help'))
						.css({top: t - 40, left: l+w+10, position: 'absolute'}).show();
				})
				.bind('blur',function(){
					$('#'+$(this).attr('help')).hide();
				});
			});
		$('.help,.expl',this.UIcontainer).hover(
			function(){$(this).find('.bubble').show();},
			function(){$(this).find('.bubble').hide();}
		);
	},	
		
	initVoting: function(){
		//voting
		$('.votes_do',this.UIcontainer).hover(
			function(){$(this).find('.do_vote').addClass('blue2 bold');},
			function(){$(this).find('.do_vote').removeClass('blue2 bold');}
		);
	}
};


function lock(locked_element){
	var loader = typeof(arguments[1])=='undefined'? true:arguments[1];
	$(locked_element).lock(loader);
}
function unlock(){
	$('.ajax_loader').remove();
}

var timeout = null;
var act_img = {};
var curFormat;
var nFormats;
$(document).ready(function(){
	Cufon.replace('h1');
	Cufon.replace('h2');
	
	ptUI.init();
	
	$('.offer img').hover(
   		function(){
   			act_img = $(this); timeout = window.setTimeout('zoom_offer()',300);
   			$('.offer .description .bubble').hide();
   		},
   		function(){window.clearTimeout(timeout); $('.offer_zoom').fadeOut('fast');}
   	);
	
	$('.offer .description span').click(function(){
		$('.offer .description span').not($(this)).next('.bubble').hide();
		$(this).next('.bubble').toggle();
	});
	
	$('.offer').bind('mouseleave',function(){$('.offer .description .bubble').hide();});
	
	$('#toggle_steps')
	.hover(function(){$(this).find('h3').css('text-decoration','underline');},function(){$(this).find('h3').css('text-decoration','none');})
	.click(function(){$('#order_steps').toggle();});

	/** Print format scroller **/
	curFormat = 0;
	nFormats = $('#ptCategoryIntro #ptFormatPreview ul li').length;
	$('#ptCategoryIntro #ptFormatPreview .vScrollBack').click(function(){
		if((curFormat-1) >= 0){
			$('#ptFormatPreview .vScrollArea').scrollTo($('#ptCategoryIntro #ptFormatPreview ul li').eq((--curFormat)), 300);
		}
		
		return false;
	});
	$('#ptCategoryIntro #ptFormatPreview .vScrollNext').click(function(){
		if((curFormat+1) < nFormats){
			$('#ptFormatPreview .vScrollArea').scrollTo($('#ptCategoryIntro #ptFormatPreview ul li').eq((++curFormat)), 300);
		}
		
		return false;
	});
	
	$('#menu_browse #nav_browse .header').click( function(){
		$('#nav_browse .nav_group').hide();
		$(this).parent().find('.nav_group').fadeIn('slow'); 
		return false;
	});
}); 

$(".nstep_head").click(function () {
    if ($("div:first").is(":hidden")) {
      $("div").slideDown("slow");
    } else {
      $("div").hide();
    }
});

function send_msg(form_id){
	var form = $('#msg_answer_'+form_id);
	var params = form.serializeArray();
	params.url = actionConf.adminSendMsgUrl;
	params.lock = '#msg_'+form_id;
	ajax(params);
}
function view_msg(elem,id){
	$(elem).find('span.bold').removeClass('bold').end().toggleClass('selected_tr');
	
	if($('tr#msg_'+id).css('display')=='none'){
		$('#msg_thread_'+id).load(actionConf.adminMsgThreadBaseUrl+'/msg/'+id,{},function(data){$('tr#msg_'+id).show();});
	}else{
		$('tr#msg_'+id).hide();
	}
}
function show_error(text){
	$('#msg > div').attr('class','error_msg').html(text);
	$('#msg').show();
	unlock();
}
function show_confirmation(text){
	$('#msg > div').attr('class','confirm_msg').html(text);
	$('#msg').show();
	unlock();
}
function hide_error(){$('#msg').hide();}

function price(val){
	val = new String(val);
	return val.replace(/\./,',');
}
function tb_showSource(thumb){
	$("#TB_window").remove();
	$("body").append("<div id='TB_window'></div>");
	$('#'+$(thumb).attr('show') + ' img').click();
}
function round(x) {
  	var k = (Math.round(x * 100) / 100).toString();
  	k += (k.indexOf('.') == -1)? '.00' : '00';
  	
  	var return_ = k.substring(0, k.indexOf('.') + 3);
  	return (typeof arguments[1]=='undefined')? return_: return_.replace(/\./,',');
}

function check_feedback_time(){
	var now = new Date();
	var cnt = Math.round(now.getTime()/1000 - s_started);
	//$('#s_counter').html(cnt);
	
	if(cnt >= 84){
		ajax({url:cfConf.checkFeedbackUrl});
	}
}
function stop_feedback_check(){
	window.clearInterval(fb_int);
}
function show_feedback_bubble(){
	$('#feedback_bubble')
		.fadeTo('slow', '0.5')
		.css('display','block')
		.hover(function(){$(this).fadeTo('fast', '1');},function(){$(this).fadeTo('fast', '0.6');});
} 
function fstep(cur,next){
	cur = $('#fb_'+ cur);
	next = $('#fb_'+ next);
	
	if($.browser.msie!==true){
		cur.fadeOut('fast',function(){
			$(this).hide();
			next.fadeIn('fast');
		});
	}else{
		cur.hide();
		next.show();
	}
}

function zoom_offer(){

	$(".offer_zoom").hide().removeClass('zr');
		
	var id = act_img.parent().parent().parent().attr('id');
	id = id.substr(1, id.length);

	$('.offer_zoom').find('tr').hide().end().find('tr#zoom_' + id).show();
	
	var window_overflow = ( act_img.offset().left + $('.offer_zoom').width() >= $(window).width() );
	var left_ = window_overflow ?
			act_img.offset().left + act_img.width() - $('.offer_zoom').width() -24 :
			act_img.offset().left ;
	
	var window_top_overflow = ( act_img.offset().top - $(window).scrollTop() >= $('.offer_zoom').height() )
	var top_ = window_top_overflow ?
			act_img.offset().top - $('.offer_zoom').height() - 39 :
			act_img.offset().top + act_img.height() + 17 - 2;
	
	var t = -17;
	var bg = 'transparent url("/img/stem_grey.png") 0 0 no-repeat';
	if (window_top_overflow) {
		t = $('.offer_zoom').height() + 20;
		bg = 'transparent url("/img/stem_grey_reverse.png") 0 0 no-repeat';
		$('.offer_zoom .stem').css({'top':t, 'background':bg});
	} else {
		$('.offer_zoom .stem').css({'top':t, 'background':bg});
	}
	
	$('.offer_zoom').css({left: left_  + 'px', top: top_ + 'px'}).addClass( (window_overflow? 'zr':'') ).fadeIn('fast');
	
}