/**
 * Main JS library for Voyo 2.0
 * If you need to override some method do it using
 *
 */

/**
 * Global variables defaults.
 */
var voyoCheckIPOK = null;
var showEwalletChargeInfo_html = null;
var voyo_get_ewallet_trans_info_pool = {};
var voyo_get_ewallet_trans_info_tmp = null;
var voyo_get_user_trans_info_pool = {};
var voyo_get_user_trans_info_tmp = null;
var ewalletBuyResp = null;
var voyoIsLoggedIn = null;
var voyoLoggedUserData = null;
var voyoUserLoginData = null;

/**
 * DOM ready calls.
 */
jQuery(document).ready(function()
{
	jQuery(".genre_column:last").addClass("last");

	// to fix layout of fullwidth boxes
	jQuery(".fw").prepend('<div class="content_border top"></div>').append('<div class="clr"></div><div class="content_border bottom"></div>');
	jQuery(".fw_wrap").append('<div class="clr"></div>');
	jQuery(".fw:last").addClass("fwb");

	var mtabActiveCarouselId = jQuery("#mtab_first_id").val();
	jQuery("#carousel-tab-"+mtabActiveCarouselId).addClass("active");
	jQuery("#"+mtabActiveCarouselId).show();

	jQuery(".multitab_carousel .ribbon h2").click(function () {
		if(jQuery(this).attr("class") != "active") {
			var c_id = jQuery(this).attr("id").replace("carousel-tab-", "");
			jQuery(".multitab_carousel .ribbon h2").removeClass("active");
			jQuery(this).addClass("active");
			/**
			  jQuery(this).parents(".ribbon").animate({
			height: 36
			  }).animate({
			height: 31
			  });
	       **/

			//jQuery(".multitab_carousel .carousel").slideUp(800);
			//jQuery("#"+c_id).slideDown(700);

			jQuery("#"+c_id).show();
			jQuery(".multitab_carousel .carousel").not(jQuery("#"+c_id)).hide();
			var scrollItems = jQuery("scroll_items_"+c_id).val();
			var itemsCount = jQuery("items_count_"+c_id).val();
			multitab_carousel_show(c_id, scrollItems, itemsCount);
		//jQuery("#"+c_id).show();
		/**
			  jQuery(".multitab_carousel .carousel-content-"+c_id).find(".items").jcarousel({
			scroll: 6,
			size: 12,
			start: 1,
			animation: 1000
			  });**/
		}
	});

	carousels_init();

	jQuery('#current-credit-amount .charge-credit, .topinfo-bubble .charge-credit, .user_account .charge-credit').die().live('click', function () {
		jQuery.get('/bin/eshop/ws/ewallet.php?x=chargeInfo', {},
			function (data) {
				var found = data.match(/<script[\s\S]+\/script>/i);
				var script = found == null ? '' : found[0];
				var content = jQuery(data).find('.content').html();
				content = script + '<div class="voyoplus-product-store-charge-credit" >' + content + '</div>';
				// jQuery.colorbox({
				// html: content,
				// onComplete : function() {
				// jQuery(this).colorbox.resize();
				// }
				// });
				lbox(content, "");
			}
			);
		return false;
	});
	
	jQuery("#ewallet-topinfo-logged-in .arrow").live("click", open_user_menu);
	jQuery("#ewallet-topinfo-logged-in .active").live("click", close_user_menu);
    
    if (location.href.indexOf("#fromRegistration") != -1) {
        jQuery.get('/bin/eshop/ws/box.php?x=userAuth&a=login&fromReg=1', function(data) {
            lbox(data, "");
        });
    }
    
    if (location.href.indexOf("#pr:") != -1) {
        show_forgotten_password_form(2); // forgotten password step 2
    }
    
    if (location.href.indexOf("#ct:") != -1) {
        show_confirmation_box();
    }
    
    if (location.href.indexOf("#showSubscribe") != -1) {
        window.location.hash = '';
        showSubscribeBox(0,0);
    }
    
    // BG Epay return
    if (location.href.indexOf("#confirmok:") != -1) {
    	ar = location.hash.split(":");
    	if (jQuery.isArray(ar)) {
    		params = ar[1].split("_");
    		url = '/bin/eshop/ws/ewallet.php?x=startTrial&step=3&trail=' + params[0] + '&paymentType=' + params[1];
    		jQuery.get(url, function(data) {
    	        lbox(data, "");
    	    });
    	}
    }
    
    if (location.href.indexOf("#confirmcancel:") != -1) {
    	ar = location.hash.split(":");
    	if (jQuery.isArray(ar)) {
    		params = ar[1].split("_");
    		url = '/bin/eshop/ws/ewallet.php?x=startTrial&step=4&trail=' + params[0] + '&paymentType=' + params[1];
    		jQuery.get(url, function(data) {
    	        lbox(data, "");
    	    });
    	}
    }
});

function closeAcountActivation()
{
	jQuery.ajax({
		async: false,
		url:'/bin/eshop/ws/user.php?x=logout&r='+Math.random(),
		type: 'POST',
		success:
			function (result) {
				if (typeof(logoutRedirectUrl) == 'undefined' || logoutRedirectUrl == '') {
					window.location.reload();
				} else {
					window.location = logoutRedirectUrl;
				}
			},
		dataType: "json"
	});
}

function show_forgotten_password_form(step)
{
    jQuery.get('/bin/eshop/ws/box.php?x=userAuth&a=forgottenPassword&step='+(step ? step : 1), function(data) {
        lbox(data, "");
	})
}

function show_confirmation_box() {
    ar = location.hash.split(":");
    jQuery.get('/bin/eshop/ws/box.php?x=confirm&ct='+ar[1], function(data) {
        lbox(data, "");
	})
}

function show_login_form()
{
	jQuery.get('/bin/eshop/ws/box.php?x=userAuth&a=login', function(data) {
        lbox(data, "");
	});
}

function show_register_form()
{
	jQuery.get('/bin/eshop/ws/box.php?x=userAuth&a=register', function(data) {
        lbox(data, "");
	});
}

function addDevice(deviceCode)
{
	jQuery.get('/bin/eshop/ws/box.php?x=device&a=add&deviceCode='+deviceCode, function(data) {
        lbox(data, "");
	});
}

function removeDevice(id)
{
	jQuery.get('/bin/eshop/ws/box.php?x=device&a=remove&id='+id, function(data) {
        lbox(data, "");
	});
}

/**
 * Ititializates all the carousels on the page.
 */
function carousels_init()
{
	var carousels = jQuery(".carousel.carouselNormal");
	if (typeof (carouselsSettings) == 'undefined') {
		carouselsSettings = [];
	}
	for (var i = 0; i < carousels.length; i++) {
		jQuery(".items", carousels[i]).jcarousel(
			carouselsSettings['id_' + carousels[i].id]
			);
	}
}

/**
 *
 */
function multitab_carousel_show(carouselId, scrollItems, itemsCount)
{
	jQuery("#" + carouselId + " .items").jcarousel({
		scroll: scrollItems,
		size: itemsCount,
		start: 1,
		animation: 1000
	});
}

/**
 *
 */
function multitab_carousel_ini(carouselId, scrollItems, itemsCount)
{
	jQuery(document).ready(function() {
		multitab_carousel_show(carouselId, scrollItems, itemsCount);
	});
}

/**
 *
 */
function add_play_overlay_button(mediaId)
{
	jQuery("#item" + mediaId + " .poster").hover(function() {
		jQuery(this).append("<div class='overlay_play_button' onclick=\"javascript: return playBonus" + mediaId + "();\"></div>")
	}, function () {
		jQuery(this).find(".overlay_play_button").remove();
	});
}

/**
 *
 */
function open_user_menu()
{
	var p_left = jQuery(this).position().left - 140;
	var p_top = jQuery(this).position().top+2;
	jQuery(".user_drop_down").css({
		left: p_left,
		top: p_top
	}).slideDown(300);
	jQuery("#ewallet-topinfo-logged-in .arrow").addClass("active");
	on_click_outside(jQuery(".user_drop_down"), close_user_menu);
}

/**
 *
 */
function close_user_menu()
{
	jQuery(".user_drop_down").hide();
	jQuery("#ewallet-topinfo-logged-in .arrow").removeClass("active");
}

/**
 * Function to execute another function when clicked outside some box
 */
function on_click_outside (box, action)
{
	jQuery("body").unbind().bind("click", function(eee) {		
        if (!jQuery.contains(box[0], eee.target)
            && jQuery.contains(document, eee.target)
            && jQuery(eee.target).is(":visible"))
        {
            // Avoid to fire event onclick_outside when user clicks on
            // the element which is inside this box
            if (typeof action == "function" && box.css("display") != "none") {
				action(box);
				eee.stopPropagation();
			}
        }
	});
}

/**
 * Displays html in simplified lightbox
 */
function lbox(input_html, after_close)
{
	var already_there = jQuery(".lbox").length;
	if (jQuery(".greyout").length == 0) {
		jQuery("body").prepend("<div class='greyout'></div>");
		jQuery(".greyout").height(jQuery("html").height());
		jQuery(".greyout").height(Math.max(
			Math.max(document.body.scrollHeight, document.documentElement.scrollHeight),
			Math.max(document.body.offsetHeight, document.documentElement.offsetHeight),
			Math.max(document.body.clientHeight, document.documentElement.clientHeight)
			));
	}
	if (already_there != 0) {
		jQuery(".lbox").remove();
	}
	jQuery(".greyout").fadeIn(300, function() {
		jQuery(".greyout").prepend("<div class='lbox_inner'><div class='clr'></div></div>");
		jQuery(".lbox_inner").prepend(input_html).wrapAll("<div class='lbox' />").before("<div class='close' title='close'>close X</div>");
		var lh = jQuery(".lbox_inner").height();
		var lw = jQuery(".lbox_inner").width();
		var wh = jQuery(window).height();
		var wtop = jQuery(window).scrollTop();
		var ltop = Math.floor(wtop + ((wh - lh) / 3));
		if (ltop < 100) {
			ltop = 100;
		}
		var lleft = (jQuery(window).scrollLeft() + jQuery(window).width() / 2 - lw / 2);
		jQuery(".lbox").css({
			display: "none",
			top: ltop,
			left: lleft,
			height: lh,
			width: lw
		});
		if (already_there != 0) {
			jQuery(".lbox").fadeIn(300);
		} else {
			jQuery(".lbox").show();
		}
		lbox_attach_close_handlers(after_close);
	});
}

/**
 * To close on close button, outside click or ESC key
 */
function lbox_attach_close_handlers(after_close)
{
	jQuery(".lbox .close").click(function() {
		lbox_close(after_close);
	});
	on_click_outside(jQuery(".lbox"), function() {
		lbox_close(after_close);
	});
	jQuery(document).keyup(function(keyup) {
		if (keyup.which == 27) {
			lbox_close(after_close);
		}
	});
}

/**
 *
 */
function lbox_close(after_close)
{
	jQuery(".lbox").fadeOut(300, function() {
		jQuery(".greyout").fadeOut(300, function() {
			jQuery(".lbox").remove();
		});
		if(typeof after_close == "function") {
			after_close();
		}
	});
}

/**
 *
 */
function fix_pagination(element)
{
	var el = jQuery(element);
	el.find(".next_page").attr("title", "next page").insertBefore(el.find(".next_set"));
	el.find(".previous_page").attr("title", "previous page").insertAfter(el.find(".previous_set"));
	el.find(".next_set").attr("title", "next set");
	el.find(".previous_set").attr("title", "previous set");
	el.find(".first").attr("title", "first");
	el.find(".last").attr("title", "last");
	var pw = (el.find(".active").offset().left - el.offset().left) * 2;
}

/**
 *
 */

function show_voyo_buy_sms(prod, unit, block, distCode) {
	var url = "/bin/eshop/ws/box.php";
	data = {
		x : "voyoModal",
		productId : prod,
		unitId : unit,
        distCode: distCode
	}
	
	jQuery.get(url, data,
            function (response) {
				var res = jQuery(response);

				checkIPOK = show_voyo_check_ip(prod, unit);
				if (checkIPOK) {
					lbox(res.filter('#voyo_modal_'+block).html(), "");
				} else {
					lbox(res.filter('#voyo_modal_geoerror').html(), "");
				}
            });
}


function show_voyo_buy(prod, unit)
{
	checkIPOK = show_voyo_check_ip(prod, unit);
	close_banner();
	mbox_open(530, 285);
	pre_fullscreen();
	if (checkIPOK) {
		jQuery('MBOX_window').innerHTML = jQuery('voyo_modal_buy').innerHTML;
	} else {
		jQuery('MBOX_window').innerHTML = jQuery('voyo_modal_geoerror').innerHTML;
	}
	return true;
}

/**
 *
 */
function show_voyo_play(prod, unit)
{
	checkIPOK = show_voyo_check_ip(prod, unit);
	close_banner();
	mbox_open(530, 187);
	pre_fullscreen();
	if (checkIPOK) {
		jQuery('MBOX_window').innerHTML = jQuery('voyo_modal_play').innerHTML;
	} else {
		jQuery('MBOX_window').innerHTML = jQuery('voyo_modal_geoerror').innerHTML;
	}
	return true;
}

/**
 *
 */
function voyo_get_ewallet_trans_info(prod, unit)
{
	prod = parseInt(prod);
	unit = parseInt(unit);
	hash = "x" + prod + "y" + unit;
	if (eval("typeof voyo_get_ewallet_trans_info_pool."+hash) == "undefined") {
		jQuery.ajax({
			async: false,
			url:'/bin/eshop/ws/ewallet.php' + '?x=trans&prod=' + prod + '&unit=' + unit + '&r='+Math.random(),
			success:
			function (result) {
				voyo_get_ewallet_trans_info_tmp = result;
			},
			dataType: "json"
		});
		eval("voyo_get_ewallet_trans_info_pool."+hash+" = voyo_get_ewallet_trans_info_tmp;");
	}
	return eval("voyo_get_ewallet_trans_info_pool."+hash);
}


/**
 *
 */
function voyo_get_user_trans_info(prod, unit)
{
	prod = parseInt(prod);
	unit = parseInt(unit);
	hash = "x" + prod + "y" + unit;
	if (eval("typeof voyo_get_user_trans_info_pool."+hash) == "undefined") {
		jQuery.ajax({
			async: false,
			url:'/bin/eshop/ws/user.php' + '?x=trans&prod=' + prod + '&unit=' + unit + '&r='+Math.random(),
			success:
			function (result) {
				voyo_get_user_trans_info_tmp = result;
			},
			dataType: "json"
		});
		eval("voyo_get_user_trans_info_pool."+hash+" = voyo_get_user_trans_info_tmp;");
	}
	return eval("voyo_get_user_trans_info_pool."+hash);
}

/**
 *
 */
function ewalletBuy(prod, unit, distCode)
{
	ewalletBuyResp = null;
	checkIPOK = show_voyo_check_ip(prod, unit);
	loggedIn = voyo_logged_in();
	hasLicense = false;
	try {
		hash = voyoPlayer.searchHash();
		hasLicense = true;
	} catch (e) {
	;
	}
	disp = "";
	if (!loggedIn) {
		disp = "nli";
	} else if (!checkIPOK) {
		disp = "gie";
	} else if (!voyoPlayer.mainVideo.paid){
		voyoPlayer.playMain();
		return false;
	} else if (hasLicense) {
		//disp = "ab";
		voyoPlayer.playMain();
		return false;
	} else {
		disp = "pi";
	}
	jQuery.ajax({
		async: false,
		url:'/bin/eshop/ws/ewallet.php',
        data: {
            x: "payInfo",
            s: disp,
            prod: prod,
            unit: unit,
            r: Math.random(),
            distCode: distCode
        },
		success:
		function (result) {
			ewalletBuyResp = result;
		},
		dataType: "json"
	});
	if (ewalletBuyResp == null) {
		return false;
	}
	lbox(ewalletBuyResp.html, "");
	return false;
}

/**
 *
 */
function voyo_logged_in()
{
	if (voyoIsLoggedIn != null) {
		return voyoIsLoggedIn;
	}
	jQuery.ajax({
		async: false,
		url:'/bin/eshop/ws/user.php' + '?x=isLoggedIn&r='+Math.random(),
		success:
		function (result) {
			voyoIsLoggedIn = result;
		},
		dataType: "json"
	});
	return voyoIsLoggedIn;
}

/**
 *
 */
function voyo_logged_user_data()
{
	if (voyoLoggedUserData != null) {
		return voyoLoggedUserData;
	}
	jQuery.ajax({
		async: false,
		url:'/bin/eshop/ws/user.php' + '?x=userData&r='+Math.random(),
		success:
		function (result) {
			voyoLoggedUserData = result;
		},
		dataType: "json"
	});
	return voyoLoggedUserData;
}

/**
 *
 */
function show_voyo_check_ip(prod, unit)
{
	if (voyoCheckIPOK != null) {
		return voyoCheckIPOK;
	}
	jQuery.ajax({
		async: false,
		url:'/bin/eshop/ws/plusPlayer.php' + '?x=checkip&prod='+prod+'&unit='+unit+'&r='+Math.random(),
		success:
		function (result) {
			voyoCheckIPOK = result;
		},
		dataType: "json"
	});

	return voyoCheckIPOK;
}

/* Converts "& @ > …" to "&amp; @ &gt; …" */
function htmlEncode(value){
  return jQuery('<div/>').text(value).html();
}

/* Converts "&amp; @ &gt; …" to "& @ > …" */
function htmlDecode(value){
  return jQuery('<div/>').html(value).text();
}

/* Shortens text inside the given jQuery object to fit given maximum width
 * objectToShorten (jQuery element) - Object to be shorten. The element must have display: block or display: inline-block for this to work properly. 
 * maxwidth (int) - maximum width the result should have
 * objectToCheck (jQuery element; optional) - Object it's width should be checked. The element should have display: block or display: inline-block for this to work properly. 
 * limit 1000 characters
 * WARNING: objectToShorten must not contain anything besides text nodes!
 * @author TR   
 */
function shorten(objectToShorten, maxwidth, objectToCheck, maxheight){
	var objectToCheck, maxheight;
	if( typeof objectToCheck == "undefined" ){
		objectToCheck = objectToShorten; 
	}
	if( typeof maxheight == "undefined" ){
		maxheight = objectToCheck.height(); 
	}
    if ( (objectToCheck.width() > maxwidth) || (objectToCheck.height() > maxheight) ){
        for (var i = 0; i<1000; i++ ){
            if ( (objectToCheck.width() > maxwidth-16) || (objectToCheck.height() > maxheight) ){
            	var content = htmlDecode( objectToShorten.html() );
                objectToShorten.html( htmlEncode( content.substr(0,content.length-1) ) );
            }
            else {
                objectToShorten.append("…");
                break;
            }
        }
    }
}

/**
 * Shows genre carousel
 */
function genreListShowList(id, params)
{
	var genreListResult = null;
	var carouselID = null;
	for (i = 0; i < params.list.length; i++) {
		jQuery('#genreListGenre' + params.list[i]).removeClass('highlighted');
	}
	jQuery('#genreListGenre' + id).addClass('highlighted');
	jQuery('#genreListShow').html('');
	jQuery.ajax({
		async: false,
		url:'/bin/eshop/ws/box.php' + '?x=genreList&id='+id+'&cnt=' + params.count + '&cht=' + params.chargingType + '&sid=' + params.subsite,
		success:
		function (result) {
			genreListResult = result;
			carouselID = jQuery(result).find("div.carousel").attr('id');
		},
		dataType: "html"
	});
	if (genreListResult != null && genreListResult != "") {
		jQuery('#genreListShow').html(genreListResult);
		jQuery('#genreListShow').addClass("fw cols6 fwcar gshow")
		.prepend('<div class="content_border top shaded"></div>')
		.append('<div class="content_border bottom"></div>')
		.animate({
			bottom:70,
			height: 328
		}, 740);
		//jQuery('#genreListShow .items').jcarousel({scroll: 6, size: 18, animation: 1000});
		jQuery("#" + carouselID + " .items").jcarousel(
			carouselsSettings['id_' + carouselID]
			);
	} else {
		jQuery('#genreListShow').removeClass("fw cols6 fwcar gshow")
		.css({
			bottom:60,
			height: 0
		})
		.html('<p>' + getTranslation('genreListErrMsg') + '</p>');

	}
	return false;
}

/**
 * Adds translation string to the global variable.
 * The parameter is an object with key as an identifier
 * and the value as a translated string.
 *
 * E.g.
 *  addTranslation({
 *		notLogged: 'You are not logged'
 *  })
 * To get this translation:
 *  getTranslation('notLogged'); // returns 'You are not logged'
 *
 * @param translation Object
 */
function addTranslation(translation)
{
	var tmpTranslations = {};
    if (typeof(translations) == "undefined") {
		translations = {};
	}
	for (key in translations) {
		tmpTranslations[key] = translations[key];
	}
	for (key in translation) {
		tmpTranslations[key] = translation[key];
	}
	translations = tmpTranslations;
}

/**
 * Returns translation string.
 * If the key is not found in the translations
 * the key is returned.
 * 
 * @param key String
 * @return String
 */
function getTranslation(key)
{
    if (typeof(translations) == "undefined") {
		translations = {};
	}
	var translated = key;
	if (key in translations) {
		translated = translations[key];
	}
	return translated;
}

/**
 * 
 */
function loadEwalletTopInfo(suffix) 
{
    
	jQuery('#ewallet_topinfo').load('/bin/eshop/ws/ewallet.php'
		+'?x=topinfo&s='+(suffix ? suffix : '')+'&r='+Math.random(),
		null,
		function (response) {
			var loggedIn = (jQuery(response).find('#ewallet-topinfo-logged-in').length > 0);
			if (!loggedIn) {
				jQuery('span.bonus-info').show();
			}
			else {
				shorten( jQuery(".ewallet-profile .fullname"), 336, jQuery(".ewallet-topinfo-text"), 20 );
			}
		}
	);

}

function voyoUserCreate(formId)
{
	jQuery('#voyoUserCreateInfo').html("");
	userChangeSubmitResult = null;
	jQuery.ajax({
		async: false,
		url:'/bin/eshop/ws/user.php?x=create&r='+Math.random(),
		type: 'POST',
		data: jQuery('#' + formId).serialize(),
		success:
			function (result) {
				voyoUserLoginData = result;
			},
		dataType: "json"
	});
	if (voyoUserLoginData.logged) {
		window.location.reload();
	} else {
		jQuery('#voyoUserCreateInfo').html("<p>"+voyoUserLoginData.msg+"</p>");
	}
	voyoUserLoginData = null;
	return false;	
}

function voyoUserEdit(formId)
{
	jQuery('#profile_right_menu').html("");
	userChangeSubmitResult = null;
	jQuery.ajax({
		async: false,
		url:'/bin/eshop/ws/user.php?x=editForm&voyo2=true&r='+Math.random(),
		type: 'POST',
		data: jQuery('#' + formId).serialize(),
		success:
			function (result) {
				jQuery('#profile_right_menu').html(result);
			},
		dataType: "html"
	});
//	if (voyoUserLoginData.logged) {
//		window.location = window.location;
//	} else {
//		jQuery('#profile_right_menu').html("<p>"+voyoUserLoginData.msg+"</p>");
//	}
//	voyoUserLoginData = null;
	return false;
}

/**
 * 
 */
function voyoUserLogin(formId) 
{
	jQuery('#voyoUserLoginInfo').html("");
	userChangeSubmitResult = null;
	jQuery.ajax({
		async: false,
		url:'/bin/eshop/ws/user.php?x=login&r='+Math.random(),
		type: 'POST',
		data: jQuery('#' + formId).serialize(),
		success:
			function (result) {
				voyoUserLoginData = result;
			},
		dataType: "json"
	});
	if (voyoUserLoginData != null && voyoUserLoginData.logged) {
		window.location.reload();
	} else {
		jQuery('#voyoUserLoginInfo').html("<p>"+voyoUserLoginData.msg+"</p>");
	}
	voyoUserLoginData = null;
	return false;	
}

/**
 * 
 */
function voyoUserLogout() 
{
	jQuery.ajax({
		async: false,
		url:'/bin/eshop/ws/user.php?x=logout&r='+Math.random(),
		type: 'POST',
		success:
			function (result) {
				if (typeof(logoutRedirectUrl) == 'undefined' || logoutRedirectUrl == '') {
					window.location.reload();
				} else {
					window.location = logoutRedirectUrl;
				}
			},
		dataType: "json"
	});
	return false;
}

/**
 * Function call stats service for tracking product consumption
 */
function product_consumption_stats(data) {
	if ( typeof data === 'string') {
		try {
			jsonData = JSON.parse(data);
		} catch (e) {}
	} else if ( typeof data === 'object') {
		jsonData = data;
	}
	if (jsonData) {
		jQuery.ajax({
			type: "GET",
			url: "/bin/service/statistic/player.php",
			timeout: 5000,
			data: {
				product: jsonData.product,
				media: jsonData.media,
				action: jsonData.action,
				playtime: jsonData.playtime,
				timeline: jsonData.timeline,
				user: jsonData.user,
				section: section_id,
				referer: window.location.host,
				pagerandom: (typeof(page_random) == 'undefined'? "0" : page_random)
			}
		});
	}
}

/**
 * Function set UT tracking extension cookie
 */
function addUTExtTrackingCookie(param) {
	var cookieVal = jQuery.cookie('ut_extension');
	if (cookieVal != null && cookieVal != '')
		cookieVal += '&' ;
	else
		cookieVal = '';
	var trackCookie = cookieVal+param;
	jQuery.cookie('ut_extension', trackCookie, {expire: "10s"});
	return trackCookie;
}

function addBoxRefererTracking(boxReferer) {
	addUTExtTrackingCookie('box='+escape(boxReferer));
}

function getUTExtTrackingCookie() {
	value = jQuery.cookie('ut_extension');
	jQuery.cookie('ut_extension', null, {path:"/"});
	return value;
}


function isUserSubscribed(callback){
    jQuery.ajax({
        url:'/bin/eshop/ws/user.php' + '?x=isUserSubscribed&r='+Math.random(),
        success:
        function (result) {
            var param = null;
            if (result.userLogged) {
                param = result.isUserSubscribed;
            }
            callback(param);
        },
        dataType: "json"
    });
}

function showSubscribeBoxFromProfile(chargingId, fromReg) {
    jQuery.get('/bin/eshop/ws/ewallet.php?x=startTrial&chargingId='+chargingId + "&fromReg=" + (fromReg ? "1" : "0"), function(data) {
        lbox(data, "");
    });
}

/*
 * fromReg - does request came from registration process
 * terminate - if user have active trial, propose termination
 */

function showSubscribeOrTerminate(chargingId, fromReg, terminate) {
    jQuery.ajax({
        url:'/bin/eshop/ws/user.php' + '?x=hasTrialActivated&r='+Math.random(),
        success:
        function (result) {
            // user is logged
            if (result.userLogged) {
                //if user is loged and has trial activated it should redirected him to his profil
                if (result.hasTrialActivated) {
                    // @TODO read from var
                	if (!terminate) {
                		window.location = '/profil';
                	} else {
                		endTrial(1);                		
                	}
                } else {
                    // else start trial
                    if (result.isUserSubscribed) {
                		window.location = '/profil';
                    } else {
	                    jQuery.get('/bin/eshop/ws/ewallet.php?x=startTrial&chargingId='+chargingId + "&fromReg=" + (fromReg ? "1" : "0"), function(data) {
    	                    lbox(data, "");
        	            });
					}
                }
            } else {
                show_login_form();
            }
        },
        dataType: "json"
    });
}

function showSubscribeBox(chargingId, fromReg) {
	showSubscribeOrTerminate(chargingId, fromReg, false);
}

function processTrial(formId) {
    jQuery.ajax({
		url:'/bin/eshop/ws/ewallet.php?x=processTrial&r='+Math.random(),
		type: 'POST',
		data: jQuery(formId).serialize(),
		success:
			function (result) {
                if (result.error) {
                  formId.errorMsg.value = result.msg;
                } else if (result.call=="subscription") {
               		showSubscribeBoxFromProfile(0,0);
                } else {
                    endTrial(2);
                }
			},
		dataType: "json"
	});
}

function svodVoucher(step) {
    loggedIn = voyo_logged_in();
    if (!loggedIn) show_login_form() 
    else {    
        jQuery.get('/bin/eshop/ws/ewallet.php?x=svodVoucher&step=' + (step ? step : "1"), function(data) {
            lbox(data, "");
        });
    }
}

function endTrial(step) {
  loggedIn = voyo_logged_in();
  if (!loggedIn) show_login_form() 
  else
  {
    var lboxClose = "";
    if (step && step == 2) {
        lboxClose = window.location.reload;
    }
    
    jQuery.get('/bin/eshop/ws/ewallet.php?x=endTrial&step=' + (step ? step : "1"), function(data) {
        lbox(data, lboxClose);
    });
  }
}

function terminateSubscription() {
    jQuery.get('/bin/eshop/ws/ewallet.php?x=endSubs', function(data) {
        lbox(data, "window.location.reload");
    });
}

function showTVODBox(productId, distCode, unitId) {
	if (jQuery("#ewallet-topinfo-logged-in").length) {
		jQuery.get('/bin/eshop/ws/ewallet.php?x=startTvod&productId='+productId+'&distCode='+distCode+'&unitId='+unitId, function(data) {
	        lbox(data, "");
		});
	} else {
		show_login_form();
	}
}

function callAccountValidation(priceId, paymentCode, trial, fromReg) {
	jQuery.get('/bin/eshop/ws/charging.php?x=accountValidation', {priceId: priceId, paymentCode: paymentCode, trial: trial, fromReg: fromReg},
			function (data) {
				if (data.type=="AJAX") {
					jQuery.get(data.url, function(data) {
						callback = function(){};
						if(paymentCode == "EWALLET"){
							callback = function(){ location.reload(true); };
						}
				    lbox(data, callback);
					});
				} else {
					window.location = data.url;
				}
			},
			"json"
		);
}

function showlbox(url, data) {
    jQuery.get(url, data,
        function (response) {
            lbox(response, "");
        });
}

function voyo_modal_check(code, check, errorMsg, productId, errorTxt1, errorTxt2) {
	if (!check.checked) {
		errorMsg.value = errorTxt1;
		jQuery(".lbox").css("height","auto");
    jQuery("#voyo_modal_play_window .warning").addClass("visible");		
		return false;
	}
	var voyo_modal_code = code;
	var voyo_modal_product = productId;
	var voyo_modal_response = null;
	jQuery.ajax({
		async: false,
		url:'/bin/eshop/ws/plusPlayer.php' + '?x=check&prod='+voyo_modal_product+'&code='+escape(voyo_modal_code),
		success:
			function (result) {
				voyo_modal_response = result;
			},
		dataType: "json"
	});
	if (voyo_modal_response != null) {
		if (voyo_modal_response.exists) {
			doNotReloadAfterLogin = true;
			//mbox_close();
			//doNotReloadAfterLogin = false;
			//voyoModalPlayHandler(voyo_modal_code);
			try {
				hash = voyoPlayer.getHash(escape(voyo_modal_code));
			} catch(e) {
				errorMsg.value = e.msg;
			}
			if(hash != "")
				renderValidityBox(voyoPlayer.getHashValidity(), function() { 
						voyoPlayer.playMain();
				});
		} else {
			errorMsg.value = voyo_modal_response.msg;
		}
	} else {
		errorMsg.value = errorTxt2;
		jQuery(".lbox").css("height","auto");
	}
	if(errorMsg.value)
		jQuery("#voyo_modal_play_window .warning").addClass("visible");
	return false;
}

function trackHomepageProductLinks () {
	jQuery(".homepage-carousels .carousel a").click(function() {
		var trackBox = jQuery(this).parents(".box").attr("class");
		var trackId = trackBox.substring(trackBox.indexOf("trckproduct"));
		addBoxRefererTracking(trackId); 
		return true;
	});
}

function callFillEwallet() {
	jQuery.get('/bin/eshop/ws/ewallet.php?x=chargeInfo', {},
			function (data) {
				var found = data.match(/<script[\s\S]+\/script>/i);
				var script = found == null ? '' : found[0];
				var content = jQuery(data).find('.content').html();
				content = script + '<div class="voyoplus-product-store-charge-credit" >' + content + '</div>';
				// jQuery.colorbox({
				// html: content,
				// onComplete : function() {
				// jQuery(this).colorbox.resize();
				// }
				// });
				lbox(content, "");
			}
	);
}

/*
 * jQuery UI Stars v3.0.1
 * http://plugins.jquery.com/project/Star_Rating_widget
 *
 * Copyright (c) 2010 Marek "Orkan" Zajac (orkans@gmail.com)
 * Dual licensed under the MIT and GPL licenses.
 * http://docs.jquery.com/License
 *
 * $Rev: 164 $
 * $Date:: 2010-05-01 #$
 * $Build: 35 (2010-05-01)
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *
 */
(function(A){A.widget("ui.stars",{options:{inputType:"radio",split:0,disabled:false,cancelTitle:"Cancel Rating",cancelValue:0,cancelShow:true,disableValue:true,oneVoteOnly:false,showTitles:false,captionEl:null,callback:null,starWidth:16,cancelClass:"ui-stars-cancel",starClass:"ui-stars-star",starOnClass:"ui-stars-star-on",starHoverClass:"ui-stars-star-hover",starDisabledClass:"ui-stars-star-disabled",cancelHoverClass:"ui-stars-cancel-hover",cancelDisabledClass:"ui-stars-cancel-disabled"},_create:function(){var C=this,F=this.options,B=0;this.element.data("former.stars",this.element.html());F.isSelect=F.inputType=="select";this.$form=A(this.element).closest("form");this.$selec=F.isSelect?A("select",this.element):null;this.$rboxs=F.isSelect?A("option",this.$selec):A(":radio",this.element);this.$stars=this.$rboxs.map(function(I){var J={value:this.value,title:(F.isSelect?this.text:this.title)||this.value,isDefault:(F.isSelect&&this.defaultSelected)||this.defaultChecked};if(I==0){F.split=typeof F.split!="number"?0:F.split;F.val2id=[];F.id2val=[];F.id2title=[];F.name=F.isSelect?C.$selec.get(0).name:this.name;F.disabled=F.disabled||(F.isSelect?A(C.$selec).attr("disabled"):A(this).attr("disabled"))}if(J.value==F.cancelValue){F.cancelTitle=J.title;return null}F.val2id[J.value]=B;F.id2val[B]=J.value;F.id2title[B]=J.title;if(J.isDefault){F.checked=B;F.value=F.defaultValue=J.value;F.title=J.title}var H=A("<div/>").addClass(F.starClass);var K=A("<a/>").attr("title",F.showTitles?J.title:"").text(J.value);if(F.split){var G=(B%F.split);var L=Math.floor(F.starWidth/F.split);H.width(L);K.css("margin-left","-"+(G*L)+"px")}B++;return H.append(K).get(0)});F.items=B;F.isSelect?this.$selec.remove():this.$rboxs.remove();this.$cancel=A("<div/>").addClass(F.cancelClass).append(A("<a/>").attr("title",F.showTitles?F.cancelTitle:"").text(F.cancelValue));F.cancelShow&=!F.disabled&&!F.oneVoteOnly;F.cancelShow&&this.element.append(this.$cancel);this.element.append(this.$stars);if(F.checked===undefined){F.checked=-1;F.value=F.defaultValue=F.cancelValue;F.title=""}this.$value=A("<input type='hidden' name='"+F.name+"' value='"+F.value+"' />");this.element.append(this.$value);this.$stars.bind("click.stars",function(H){if(!F.forceSelect&&F.disabled){return false}var G=C.$stars.index(this);F.checked=G;F.value=F.id2val[G];F.title=F.id2title[G];C.$value.attr({disabled:F.disabled?"disabled":"",value:F.value});D(G,false);C._disableCancel();!F.forceSelect&&C.callback(H,"star")}).bind("mouseover.stars",function(){if(F.disabled){return false}var G=C.$stars.index(this);D(G,true)}).bind("mouseout.stars",function(){if(F.disabled){return false}D(C.options.checked,false)});this.$cancel.bind("click.stars",function(G){if(!F.forceSelect&&(F.disabled||F.value==F.cancelValue)){return false}F.checked=-1;F.value=F.cancelValue;F.title="";C.$value.val(F.value);F.disableValue&&C.$value.attr({disabled:"disabled"});E();C._disableCancel();!F.forceSelect&&C.callback(G,"cancel")}).bind("mouseover.stars",function(){if(C._disableCancel()){return false}C.$cancel.addClass(F.cancelHoverClass);E();C._showCap(F.cancelTitle)}).bind("mouseout.stars",function(){if(C._disableCancel()){return false}C.$cancel.removeClass(F.cancelHoverClass);C.$stars.triggerHandler("mouseout.stars")});this.$form.bind("reset.stars",function(){!F.disabled&&C.select(F.defaultValue)});A(window).unload(function(){C.$cancel.unbind(".stars");C.$stars.unbind(".stars");C.$form.unbind(".stars");C.$selec=C.$rboxs=C.$stars=C.$value=C.$cancel=C.$form=null});function D(G,I){if(G!=-1){var J=I?F.starHoverClass:F.starOnClass;var H=I?F.starOnClass:F.starHoverClass;C.$stars.eq(G).prevAll("."+F.starClass).andSelf().removeClass(H).addClass(J);C.$stars.eq(G).nextAll("."+F.starClass).removeClass(F.starHoverClass+" "+F.starOnClass);C._showCap(F.id2title[G])}else{E()}}function E(){C.$stars.removeClass(F.starOnClass+" "+F.starHoverClass);C._showCap("")}this.select(F.value);F.disabled&&this.disable()},_disableCancel:function(){var C=this.options,B=C.disabled||C.oneVoteOnly||(C.value==C.cancelValue);if(B){this.$cancel.removeClass(C.cancelHoverClass).addClass(C.cancelDisabledClass)}else{this.$cancel.removeClass(C.cancelDisabledClass)}this.$cancel.css("opacity",B?0.5:1);return B},_disableAll:function(){var B=this.options;this._disableCancel();if(B.disabled){this.$stars.filter("div").addClass(B.starDisabledClass)}else{this.$stars.filter("div").removeClass(B.starDisabledClass)}},_showCap:function(B){var C=this.options;if(C.captionEl){C.captionEl.text(B)}},value:function(){return this.options.value},select:function(D){var C=this.options,B=(D==C.cancelValue)?this.$cancel:this.$stars.eq(C.val2id[D]);C.forceSelect=true;B.triggerHandler("click.stars");C.forceSelect=false},selectID:function(D){var C=this.options,B=(D==-1)?this.$cancel:this.$stars.eq(D);C.forceSelect=true;B.triggerHandler("click.stars");C.forceSelect=false},enable:function(){this.options.disabled=false;this._disableAll()},disable:function(){this.options.disabled=true;this._disableAll()},destroy:function(){this.$form.unbind(".stars");this.$cancel.unbind(".stars").remove();this.$stars.unbind(".stars").remove();this.$value.remove();this.element.unbind(".stars").html(this.element.data("former.stars")).removeData("stars");return this},callback:function(C,B){var D=this.options;D.callback&&D.callback(this,B,D.value,C);D.oneVoteOnly&&!D.disabled&&this.disable()}});A.extend(A.ui.stars,{version:"3.0.1"})})(jQuery);

