try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {}
var defaultInputValues = new Array();

$(function() {
	// image preload
	$.preloadImages(_appRoot + "/images/loader-small.gif", _appRoot + "/images/loader-large.gif");
	
	// auto clear input fields
	$(".autoClear").each(function(index){
		defaultInputValues[index] = $(this).val();
		$(this).focus(function() { if ($(this).val() == defaultInputValues[index]) { $(this).val('') } }).blur(function(){if ($(this).val()=='') {$(this).val(defaultInputValues[index])}})});

	// round input field
	$("input.round-field").wrap($("<div>").addClass("round-field-container")).before($("<div>").addClass("round-field-left")).after($("<div>").addClass("clear")).after($("<div>").addClass("round-field-right"));
	$("a.round-link").wrapInner("<span></span>").before($("<img>").attr("src", _appRoot+"/images/background/round-link-left.jpg").addClass("round-link")).after($("<img>").attr("src", _appRoot+"/images/background/round-link-right.jpg").addClass("round-link"));
	// form submition
	$("#registration a.submit, #subscription a.submit, #issue a.submit, #epay a.submit, #g2s a.submit, #share a.submit").click(function(){$(this).closest("form").submit(); return false;});
	
	// login drop panel
	$("a.login").click(function(){$("#header form.login").slideToggle("fast").css("top", $(this).position().top + 20);});
	$("form.login .minimize").click(function(){$("form.login").slideUp("fast")});
	
	// reader popup
	$(".buy").click(function() { alert('За да разгледате списанието е нужно да го закупите!');});
	$(".register").click(function() { alert('За да разгледате списанието е нужно да се регистрирате!');});
	$(".reader").click(function() {
	/*
		url = _appRoot + '/reader/magazine.php?id=' + $(this).attr('rel');
		screenSize = Util.getScreenResolution();
		popup(url, screenSize.width, screenSize.height);
		return false;
	*/
		params  = 'width='+screen.width;
		params += ', height='+screen.height;
		params += ', top=0, left=0'
		params += ', fullscreen=yes';
		url = _appRoot + '/reader/reader.php?id=' + $(this).attr('rel');
		newwin=window.open(url,'reader', params);
		if (window.focus) {newwin.focus()}
		return false;
	});

	// student checkbox
	$("#is_student").change(function() { $("#periodLength").attr("disabled", $(this).attr("checked") ? "disabled" : "").find("option[value=12]").attr("selected", "selected"); });
	
	// country drop down
	$("#country").change(function() { if ($(this).find("option:selected").val() == 1) { $("input[name='object[type]']").removeAttr("disabled"); } else { $("input[name='object[type]']").attr("disabled", "disabled").eq(1).removeAttr("disabled").attr("checked", "checked"); }});
	
	// shipping country
	$("#shippingCountry").change(function() {
		var val = $(this).find("option:selected").val();
		if (val == 1) {
			$("#type_1").removeAttr("disabled");
		} else {
			$("#type_1").attr("disabled", "disabled");
		}
	}).trigger('change');
	
	
	// alert status
	if (isDefined('alertMessage') && alertMessage != '') { alert(alertMessage); }
	
	// shopping cart
	$("#cart img.minus, #cart img.plus, #cart img.del").click(function() {
		$method = $(this).attr('class');
		$id = $(this).attr('alt');
		$(this).closest("form").find("input[name='method']").val($method).end().find("input[name='id']").val($id).end().submit();
	});
	
	// textarea
	$('textarea').countable({threshold: 0, startOpacity: 0.75, interval: 200, maxLength: 200, positiveCopy: 'Оставащи символи: {n}', negativeCopy: 'Превишени символи: {n}'});
	$('textarea.resize').autoResize({ animateDuration :150, extraSpace : 10 });
	
	// newsletter
	$("#newsletter a").click(function(){ $(this).closest("form").find("input[name='method']").val($(this).attr('rel')).end().submit(); });
	$("#newsletter form").submit(function(){ 
		var param = $(this).serialize();
		$.post(_appRoot+'/'+_lang+'/ajax/newsletter.php', param , function(data){ alert(data.message); }, "json");
		return false;
	});
	
	// fancybox init
	if ($.isFunction($.fn.fancybox)) {
		var fb_opt = {'overlayShow': true, 'overlayOpacity': 0.70, 'zoomSpeedIn' : 300, 'zoomSpeedOut' : 400, 'frameWidth': 330, 'frameHeight': 450};
		$("a.popup").fancybox(fb_opt);
	}

	if (isDefined("productId")) {
		// comments
		commentInit();
		
		// rating
		ratingInit();
	}
	
	// coverflow
	$(".coverflowControl a").click(function(){updateCoverflow($(this).attr('rel')); return false; });
	
	//search
	$("#toolbar form").submit(function() {
		var action = _appRoot + "/" + $(this).find("option:selected").eq(0).val();
		$(this).attr("action", action);
		return true;
	});
	$(".search form fieldset a").click(function() {
		$(this).closest("form").find("input[name='type']").val($(this).attr("rel"));
		$(".search form fieldset a").removeClass("active");
		$(this).addClass("active");
		$(this).closest("form").submit();
	});
});

jQuery.preloadImages = function() {
  for(var i = 0; i<arguments.length; i++) {
    jQuery("<img>").attr("src", arguments[i]);
  }
}
function commentInit() {
	commentLoad(productId, 1);
	$("#commentPaging a").live("click", commentChangePage);
	$("#add-comment a").one("click", commentAdd);
}
function commentLoad(id, page) {
	$("#comments ul").remove();
	$("#comments .loader").show();
	$.post(_appRoot+'/'+_lang+'/ajax/comment.php', {method:'get',id:id,p:page} , function(data){ 
		$("#comments ul").remove();
		$("#comments .loader").hide();
		$("#commentPaging").html(data.paging);
		if (data.items.length > 0) {
			$("#comments").append($("<ul>"));
			$.each(data.items, function(i,item){
				$("#comments ul").append($("<li>").html(item));
			});
			$("#comments ul").show("fast");
		}
		if (data.items.length > 0 || _logged) {
			$("#commentHeading").show();
		} else {
			$("#commentHeading").hide();
		}
	}, "json");
}
function commentChangePage() {
	var page = $(this).attr('rel');
	commentLoad(productId, page);
}
function commentAdd() {
	var text = $.trim($("#add-comment textarea").val());
	if (text.length > 5) {
		$("#add-comment textarea").attr("disabled", "disabled");
		$.post(_appRoot+'/'+_lang+'/ajax/comment.php', {method:'add',id:productId,text:text} , function(data){ 
			commentLoad(productId, 1);
			$("#add-comment").hide();
		});
	} else {
		alert("Невалиден коментар!");
	}
}
function ratingInit() {
	ratingLoad(productId);
	$(".rating a").live("click", ratingVote);
}
function ratingLoad(id) {
	$(".rating ul").remove();
	$(".rating .loader").show();
	$.post(_appRoot+'/'+_lang+'/ajax/rating.php', {method:'get',id:id} , function(data){
		$(".rating ul").remove();
		$(".rating .loader").hide();
		$(".rating").append(data);
	}, "json");
}
function ratingVote() {
	var vote = parseInt($(this).attr("rel"));
	$(".rating .loader").show();
	$.post(_appRoot+'/'+_lang+"/ajax/rating.php", {method:'add',id:productId,vote:vote},
  function(data){
		$(".rating ul").remove();
		$(".rating .loader").hide();
		$(".rating").append(data);
  }, "json");
}
function updateBook(id) {
	$(".coverflowControl a").removeClass("active").filter("[rel='"+id+"']").addClass("active");
	$.post(_appRoot+'/'+_lang+'/ajax/book.php', {method:'get',id:id} , function(data){
		$("#book a.read").attr('rel', data['id']);
		$("#book a.share").attr('href', _appRoot+'/share?id='+data['id']);
		$("#book h1").text(data['title']);
		$("#book h2").text(data['date']);
		$("#book p.attrib:eq(0) strong span").text(data['price0']);
		$("#book p.attrib:eq(1) strong span").text(data['price1']);
		$("#book a.order").attr('href', data['url']);
		$("#book .text").html(data['text']);
		window.document.title = data['window_title'] + " " + _title;
		ratingLoad(id);
		commentLoad(id);
	}, "json");
}
function updateCoverflow(id) {
	updateBook(id);
	//if ($("#coverflow").size() > 0 && typeof($("#coverflow")[0].updateCoverflow) != 'undefined') {
		$("#coverflow")[0].updateCoverflow(id);
	//}
}
function isDefined(variable) {
	return (typeof(window[variable]) == 'undefined') ? false : true;
}