function r(str) {
    return str;
}
function refresh(url) {
    return document.location.href = url;
}

function leftmenu_toggle(section_id) {
    var section = $(section_id);
    if (section.hasClass('closed')) {
        // Open this menu 
        section.removeClass('closed');
        $('.MAL_listmenuarea', section).slideDown('fast', function() { compensateColumnHeights(); });
        createCookie(section_id.substring(1)+'_closed','0',30);
    } else {
        // Close this menu
        section.addClass('closed');
        $('.MAL_listmenuarea', section).slideUp('fast', function() { compensateColumnHeights(); });
        createCookie(section_id.substring(1)+'_closed','1',30);
    }
    
}

$(document).ready(function () {
	$('#bb-listitem-genres').hover(
        function () { bluebar.open("bluebar_submenu_genres"); },
		function () { bluebar.close("bluebar_submenu_genres"); }
    );
    $('#bb-listitem-prio').hover(
        function () { bluebar.open("bluebar_submenu_prio"); },
		function () {  bluebar.close("bluebar_submenu_prio"); }
    );
    $('#bb-listitem-filter').hover(
        function () {  bluebar.open("bluebar_submenu_filter"); },
		function () { bluebar.close("bluebar_submenu_filter"); }
    );
    
    var SiteSearchInput = $('#SiteSearchInput');
    if (SiteSearchInput.length > 0)  {
        SiteSearchInput.keyup(function(event){
            return SiteSearch.keyUp(event);
        });
        SiteSearchInput.focus();
        /* 
        SiteSearchInput.blur(function(event){
            t = setTimeout('SiteSearch.hide()',200);
        });
         */
    }
    // Load on scroll
    $(window).bind('scroll', function() {
      loadBoxImgs();
    });
    loadBoxImgs();
});

function compensateColumnHeights() {
    if ($('#mainAreaLeftCol') && $('#mainAreaRightCol')) {
        $('#MAL_menu').css({'height' : 'auto'});
        $('#MAR_stage').css({'height' : 'auto'});
        var left_height = $('#mainAreaLeftCol').height();
        var right_height = $('#mainAreaRightCol').height();
        if (right_height < left_height) {
            // Adjust right column
            $('#MAR_stage').css({'height' : (left_height-148)+'px'});
        } 
        if (left_height < right_height) {
            // Adjust menu column
            $('#MAL_menu').css({'height' : (right_height-60)+'px'});
        }
    }
}

function loadBoxImgs() {
    var scrollTop = $(document).scrollTop();
    var innerHeight = $(document).height();
    var scrollBottom = scrollTop + innerHeight;
    var imgs = $('.loadonscroll');    
    for(var i=0;i<imgs.length;i++) {
        var img_el = $(imgs[i]);
        var imagePos = img_el.position();
        var imageSrc = imgs[i].src;
        if (imageSrc.indexOf("spacer.gif") > 0 && imagePos.top > scrollTop && imagePos.top < scrollBottom) {
            // imgs[i].src = imgs[i].alt;
            
            if ($.browser.msie) {
                imgs[i].src = imgs[i].alt;
            } else {
                $(imgs[i]).css({'display': 'none'});
                imgs[i].src = imgs[i].alt;
                $(imgs[i]).fadeIn('fast');
            }
        }
    }
}

var bluebar = {
    open_timer : null,
    close_timer : null,
    open : function(ref_id) {
        bluebar.submenu_hideall(ref_id);
        clearTimeout(bluebar.open_timer);
        clearTimeout(bluebar.close_timer);
        bluebar.open_timer = setTimeout('bluebar.submenu_show("' + ref_id + '")',200);
    },
    close : function(ref_id) {
        clearTimeout(bluebar.open_timer);
        //clearTimeout(bluebar.close_timer);
        bluebar.close_timer = setTimeout('bluebar.submenu_hide("' + ref_id + '")',1000);
    },
    submenu_show : function(ref_id) {
		var offset = $('.bluebar_container').offset();
        $("#"+ref_id).css({left: offset.left});
        $("#"+ref_id).fadeIn('fast');
	},
	submenu_hide : function(ref_id) {
		$("#"+ref_id).hide();
	},
    submenu_hideall : function(except_id) {
        $(".bb_list li ul").each(function() {
            if ($(this).attr('id') != except_id) {
                $(this).hide();
            }
        });
    }
};

function hwide_click(el) {
    el = $(el);
    if (el.hasClass("hw_top_cat")) {
        
    } else if (el.hasClass("hw_sub_cat")) {
        
    } else if (el.hasClass("hw_search_q")) {
        
    }
}

function ratingHTML(score) {
	return '<div class="rating_big"><div class="rating_inner" style="width: '+score+'%;"></div></div>';
}

function productHTML(params) {
    
    if (typeof(params) != 'object') params = {};
    if (typeof(params.sku) == 'undefined') params.sku = '';
    if (typeof(params.url_name) == 'undefined') params.url_name = '';
    if (typeof(params.title) == 'undefined') params.title = 'Untitled';
    if (typeof(params.info) == 'undefined') params.info = null;
    if (typeof(params.gg_rating) == 'undefined') params.gg_rating = 0;
    if (typeof(params.boximg) == 'undefined') params.boximg = 0;
    if (typeof(params.price) == 'undefined') params.price = '';
    if (typeof(params.price_html) == 'undefined') params.price_html = '';
    if (typeof(params.srp) == 'undefined') params.srp = 0;
    if (typeof(params.rel) == 'undefined') params.rel = '';
    if (typeof(params.id) == 'undefined') params.id = '';
    if (typeof(params.add_class) == 'undefined') params.add_class = '';
    var title_max_char = (params.add_class == 'thumb') ? 16 : 22;
    
    if (params.srp > params.price) {
        var discount = Math.round((params.srp/params.price)*100, 2);
        var tag_add_class = 'redbg';
    } else {
        var discount = 0;
        var tag_add_class = '';
    }
    
    
    var html = '';
    
    html += '<div ';
    if (params.rel != '')  html += ' rel="'+params.rel+'"';
    if (params.id != '')  html += ' id="'+params.id+'"';
    html += 'class="product_display '+params.add_class+'">';
        html += '<div class="box_cont">';
            html += '<a href="/'+params.sku+'/'+params.url_name+'" title="'+params.title+'">';
            html += '<img src="';
            if (params.add_class.indexOf('thumb') >= 0) {
                if (params.boximg) {
                    html += '/img/boximgs/thumb/'+params.sku+'.jpg';
                } else {
                    html += '/img/404_boxshot_thumb.gif';
                }
            } else {
                if (params.boximg) {
                    html += '/img/boximgs/122x177/'+params.sku+'.jpg';
                } else {
                    html += '/img/404_boxshot_thumb.gif';
                }
            }
            html += '" border="0" />';
            html += '</a>';
        html += '</div>';
        
        html += '<div class="descr_cont">';
            if (params.info == null) {
                html += '<a href="/'+params.sku+'/'+params.url_name+'" class="ttl" title="'+params.title+'">'+params.title+'</a>';
            }
            html += '<div class="lnks">';
                html += '<div>'+params.price_html+'</div>';
                if (params.price == 0) {
                    html += '<div class="buytag '+tag_add_class+'"><a href="/account/add_remove?add='+params.sku+'" title="'+r("Add")+' '+params.title+' '+r("to account")+'">'+r("Add")+'</a></div>';
                } else {
                    html += '<div class="buytag '+tag_add_class+'"><a href="/shop/addtocart?sku='+params.sku+'" title="'+r("Buy")+' '+params.title+'">'+r("Buy")+'</a></div>';
                }
                if (params.add_class.indexOf('thumb') < 0) {
                    html += '<div class="infotag"><a href="/'+params.sku+'/'+params.url_name+'" onclick="return display_product_preview(\''+params.sku+'\')" title="'+r("Product information")+'">';
                    html += '<img src="/img/spacer.gif" border="0" width="24" heigth="15" alt="'+r("Product information")+'" />';
                    html += '</a></div>';
                }
            html += '</div>';
        html += '</div>';
        
        if (params.add_class.indexOf('thumb') < 0 && params.info != null) {
            html += '<div class="info_cont">';
                html += ratingHTML(params.gg_rating);
                if (params.gg_rating > 0) {
                    var rating = Math.round(params.gg_rating/20, 1);
                    html += '<p class="rating_descr">'+rating+' '+r('Rating')+'</p>'
                } else {
                    html += '<p class="rating_descr">'+r('Not rated')+'</p>'
                }
                html += '<h3><a href="/'+params.sku+'/'+params.url_name+'" title="'+params.title+'">'+params.title+'</a></h3>';
                html += params.info;
            html += '</div>';
        }
        
    html += '</div>';
    
    return html;
}


var ProductPage = {
    toggle_info : function (link_el) {
        var container_height = $(link_el+' .textcontainer').height();
        var text_height = $(link_el+' .textcontainer .inner').height();
        if ($(link_el).hasClass('expanded')) {
            // Hide
            if (container_height > 150) {
                var diff = container_height-150;
                var anim_time = diff*3;
                $(link_el+' .textcontainer').animate({height: '150px'}, anim_time, function() { 
                    $(link_el).removeClass('expanded');
                    $(link_el +  ' .moreless a').html(r('More'));
                });
            }
        } else {
            // expand
            if (text_height > container_height) {
                var diff = text_height - container_height;
                var anim_time = diff*3;
                $(link_el+' .textcontainer').animate({height: text_height+'px'}, anim_time, function() { 
                    $(link_el).addClass('expanded');
                    $(link_el +  ' .moreless a').html(r('Less'));
                });
            }
        }
    },
    showSysreq : function () {
        $('#system_req_btn').hide();
        $('#system_req').slideDown();
    }
}

function faq_toggle(el, t) {
    if ($(el+' .hidden_content'+t).hasClass('expanded')) {
        // hide
        $(el+' .hidden_content'+t).slideUp('fast');
        $(el+' .hidden_content'+t).removeClass('expanded');
        if (t=='.faqcat') {
            $('.moreless', $(el)).removeClass('less').html(r('More'));
        }
    } else {
        // expand
        $(el+' .hidden_content'+t).slideDown('fast');
        $(el+' .hidden_content'+t).addClass('expanded');
        if (t=='.faqcat') {
            $('.moreless', $(el)).addClass('less').html(r('Less'));
        }
    }
    return false;
}

function display_info(label) {
    var url = '/internal-apis/site/info?label=' + label;
    $.get(url, function (resp) {
        $.fancybox(resp, {'autoDimensions' : false, 'width' : 600, 'height' : 300, 'padding' : 1 });
    });
    return false;
}
function display_video(video_id) {
    var url = '/internal-apis/site/video?video_id=' + video_id;
    $.get(url, function (resp) {
        $.fancybox(resp, {'autoDimensions' : false, 'width' : 680, 'height' : 500, 'padding' : 1});
    });
    return false;
}
function display_product_preview(sku) {
    var url = '/internal-apis/site/product_info?sku=' + sku;
    $.get(url, function (resp) {
        $.fancybox(resp, {'autoDimensions' : false, 'width' : 740, 'height' : 650, 'padding' : 1});
    });
    return false;
}
function display_messages_compose(reply) {
    if (typeof reply == 'undefined') reply = 0;
    var url = '/internal-apis/site/messages_compose?reply=' + reply;
    $.get(url, function (resp) {
        $.fancybox(resp, {'autoDimensions' : false, 'width' : 740, 'height' : 350, 'padding' : 1});
    });
    return false;
}
function review_form(sku) {
    var url = '/internal-apis/site/review_form?sku=' + sku;
    $.ajax(url, {
        method: 'get',
        success : function (resp) {
            $.fancybox(resp, {'autoDimensions' : false, 'width' : 740, 'height' : 300, 'padding' : 1});
        }
    });
    return false;
}

function confirm_checkout(confirm_double_item) {
    var msg = '';
    // Confirm double copies
    if (confirm_double_item) {
        msg = r('You are about to purchase two copies of the same product. Please note that no refunds are given for accidental duplicates. Click OK to confirm your order and continue.');
        if (!confirm(msg)) return false;
    }
	var agreements = document.getElementsByName("agreement");
	if (agreements) {
		for (var i = 0; i < agreements.length; i++) {
			if (!agreements[i].checked) {
				alert(r('You must read and accept all License Agreements.'));
				return false;
			}
		}
	}

	if (!$("#checkout input:radio:checked").length) {
		alert(r('Please select a payment method.'));
		return false;
	}
    
    if (!$("#accept_policy:checked").length) {
        alert(r('You must accept the Terms of use and the Refund policy.'));
        return false;
    }
    
	return true;
}

var rating = {
	rating_inner_id : "",
	activate : function(rating_inner_id,par) {
		rating.rating_inner_id = rating_inner_id;
		div = $(rating.rating_inner_id + ' .rating_myvote');
        var pos = $(par).position();
		div.css({position: 'absolute', left: pos.left+"px", top: pos.top+"px", display: 'block'});
	},
	over : function (score) {
		var children = $(rating.rating_inner_id+'  .rating_myvote a');
		for (var i=0; i<5; i++) {	
			if (i<score)
				children[i].className = "";
			else
				children[i].className = "hidden";
		}
	},
	inactivate : function(rating_inner_id) {
		var div = $(rating_inner_id + ' .rating_myvote');
		div.css({display: 'none'});
	},
	vote : function(sku,score) {
		var url = "/rateProduct?sku=" + sku + "&score=" + score;
        $.ajax({
            url : url,
            dataType : 'html',
            success: function (resp) {
                var w = score*20;
                $(rating.rating_inner_id).css({"width": w+"%"});
                alert(resp);
                Notifications.check();
            }
        });
		return false;
	}
}

function showRegisterFields() {
	$("#login_fields").html("").hide();
	var url = "/internal-apis/site/registration_form_elements";
	$.get(url, function(resp) {
        $("#reg_account").html(resp).show();
    });
	return false;
}

var shoppingCart = {
	items : [],
	selectedItem : 0,
	notifierTimer : 0,
	addItem : function(sku,gift) {
        /* 
		var url = "/shop/addtocart?ajax=1&sku=" + sku + "&gift=" + gift;
		new Ajax.Request(url, 
			{
				method: 'get',
				onSuccess: function(req) {
					if (req.responseText == "1") {
                        window.location.href = "/shop/checkout";
					} else {
						alert(req.responseText);
					}
				}
			});
         */
		// return false;
	},
	loadItem : function(itemId) {
		var url = "/internal-apis/site/shoppingcart_getitem?itemId=" + itemId + "&selectedItem=" + shoppingCart.selectedItem;
		$.get(url, function(resp) {
            // Update item
            $("#sc_item").html(resp);
            
            // Get current_cart_id
            var matches = resp.match('<!--(.*)-->');
            var current_cart_id = (typeof matches[1] != 'undefined') ? matches[1] : 0;
            if (current_cart_id > 0) {
                // Update buttons
                var cart_btn_mid = $("#cart_btn_mid");
                cart_btn_mid.attr({
                    href : '/shop/removefromcart?itemId=' + current_cart_id + '&ref=1',
                    onclick : 'return shoppingCart.removeItem(' + current_cart_id + ');'
                });
                
                // Set selected item
                shoppingCart.selectedItem = current_cart_id;
            }
        });
	},
	removeItem : function(itemId) {
		var url = "/shop/removefromcart?itemId=" + itemId;
		new Ajax.Request(url, function(req) {
            if (location.href.indexOf("/shop/checkout") > 0) {
                window.location.href = "/shop/checkout";
            } else {
                shoppingCart.loadItem("%");
            }
		});
		return false;
	},
	updateView : function(html) {
		
		// shoppingCart.open();
	},
	scrollToCart : function() {
		//scrollTo("#Shoppingcart",{offset: -50});
	},
	toggle : function() {
        /* 
		if ($("#Shoppingcart").getStyle("display") == "none") {
			Effect.BlindDown('shoppingcart' , { duration: 0.3 });
		} else {
			Effect.BlindUp('shoppingcart' , { duration: 0.3 });
		}
		return false;
         */
	},
	open : function() {
        /* 
		if ($("shoppingcart").getStyle("display") == "none") {
			Effect.BlindDown('shoppingcart' , { duration: 0.3 });
		}
         */
	},
	close : function() {
        /* 
		if ($("shoppingcart").getStyle("display") == "block") {
			Effect.BlindUp('shoppingcart' , { duration: 0.3 });
		}
         */
	}
}

var ReleaseCountdown = {
    container : '#releasecountdown',
    sec_left : 0,
    init : function(sec_left, container) {
        this.sec_left = sec_left;
        if (typeof container != 'undefined') this.container = container;
        this.upd();
    },
    upd : function() {
        var sec_left = this.sec_left;
        
        var days = Math.floor(sec_left / 86400);
        var hours = Math.floor((sec_left-(days*86400)) / 3600);
        var mins = Math.floor((sec_left-(days*86400)-(hours*3600)) / 60);
        var secs = Math.floor((sec_left-(days*86400)-(hours*3600)-(mins*60)));
        
        // Update HTML
        var html = '';
        
        if (days<10) days = '0'+days;
        if (hours<10) hours = '0'+hours;
        if (mins<10) mins = '0'+mins;
        if (secs<10) secs = '0'+secs;
        
        if (days>0) {
            html += days+' <span class="unitword">DAYS</span> ';
        } else {
            html += '00 <span class="unitword">DAYS</span> ';
        }
        
        if (hours>0 || days>0 || days>0) {
            html += hours+' <span class="unitword">HOURS</span> ';
        } else {
            html += '00 <span class="unitword">HOURS</span> ';
        }
        if (mins>0 || (hours+days) > 0) {
            html += mins+' <span class="unitword">MINUTES</span> ';
        } else {
            html += '00 <span class="unitword">MINUTES</span> ';
        }
        html += secs+' <span class="unitword">SECONDS</span> ';
        
        $(this.container).html(html);
        
        // countdown
        this.sec_left = this.sec_left-1;
        setTimeout("ReleaseCountdown.upd();", 1000);
    }
}

var Offercountdown = {
    sec_left : 0,
    init : function(sec_left) {
        Offercountdown.sec_left = sec_left;
        Offercountdown.upd();
    },
    upd : function() {
        var sec_left = Offercountdown.sec_left;
        
        var days = Math.floor(sec_left / 86400);
        var hours = Math.floor((sec_left-(days*86400)) / 3600);
        var mins = Math.floor((sec_left-(days*86400)-(hours*3600)) / 60);
        var secs = Math.floor((sec_left-(days*86400)-(hours*3600)-(mins*60)));
         
        
         
        // Update HTML
        var html = '<span';
        if (days==0) html += ' class="red bold"';
        else html += ' class="textcolor1"';
        html += '>';
        html += r('Offer expires in')+' ';
        if (days>0) {
            
            html += days+' '+r('days');
            if (hours>0) {
                html += ' '+r('and')+' '+hours+' '+r('hours');
            }
            
        } else {
            
            if (days<10) days = '0'+days;
            if (hours<10) hours = '0'+hours;
            if (mins<10) mins = '0'+mins;
            if (secs<10) secs = '0'+secs;
            
            if (hours>0 || days>0) {
                html += hours+':';
            } else {
                html += '00:';
            }
            if (mins>0 || (hours+days) > 0) {
                html += mins+':';
            } else {
                html += '00:';
            }
            if (days == 0) {
                html += secs;
            }
        }
        
        html += '</span>';
        
        $('#offercountdown').html(html);
        
        // countdown
        if (days==0) {
            Offercountdown.sec_left = Offercountdown.sec_left-1;
            setTimeout("Offercountdown.upd();", 1000);
        }
    }
}

function mygames_fetchserial(params) {
    //if (confirm("After a serial key has been shown, you no longer have the right to request a refund. \nDo you want to proceed and show this serial key now?")) {
        
        var url = "/internal-apis/site/serials/fetch?pb_id=" + params.pb_id + "&sku=" + params.sku + "&serial_id=" + params.serial_id + "&upd_el="+params.upd_el;
        $.ajax(url, {
            method : 'get',
            success : function (resp) {
                var data = eval('(' + resp + ')');
                if (typeof(data.errmsg) != "undefined") {
                    alert(data.errmsg);
                } else if (typeof(data.upd_el) != "undefined" && typeof(data.html) != "undefined") {
                    $('#'+data.upd_el).html(data.html);
                } else {
                    alert(r('Could not show the serial key(s)'));
                }
            }
        });
        
        mygames_hidegiftbtn(params.pb_id);
        
    //}
    return false;
}
function mygames_hidegiftbtn(pb_id) {
    var giftbtn = $("#giftgamebtn"+pb_id);
    if (giftbtn) {
        giftbtn.hide();
    }
}

function blueinfo_toggle(id) {
    if ($(id).hasClass("expanded")) {
        $(".moreinfo", $(id)).slideUp("fast");
        $(id).removeClass("expanded");
    } else {
        $(".moreinfo", $(id)).slideDown("fast");
        $(id).addClass("expanded");
    }
}

function FacebookLogin(){
  FB.login(function(response) {
      if (response.authResponse) {
          window.location.href = window.location.href;
      } else {
        alert('Login failed!');
        return false;
      }
    }, {scope:'read_stream,publish_stream,user_likes'}); // 
}
function LoginWithFacebook(){
  FB.login(function(response) {
      if (response.authResponse) {
          window.location.href = window.location.href+'?facebook_login=1';
      } else {
        alert('Login failed!');
        return false;
      }
    }, {scope:'read_stream,publish_stream,user_likes'}); // 
}
function FacebookOnRequestPermission(){
  FB.login(function(response) {
      if (response.authResponse) {
		// user is logged in and granted some permissions.
		window.location.href = "/account/facebook?connect";
      } else {
        // user is not logged in
        alert(r('Not logged in or not authorized'));
      }
    }, {scope:'read_stream,publish_stream,user_likes'}); // 
}

// Gifting
function GC_SelectBuddy(pb_id) {
    var buddy_select = $("#buddy_id" + pb_id);
    if (buddy_select.val() != "") {
        $("#to_email" + pb_id).val('');
        GC_enterEmailAddr(pb_id);
    }
}
function GC_enterEmailAddr(pb_id) {
    var to_email = $("#to_email" + pb_id);
    if (to_email.val() == '') {
        $("#sendGiftForm" + pb_id).css({'display':'none'});
        $("#sendGiftForm" + pb_id).removeClass("open");
    } else if (!$("#sendGiftForm" + pb_id).hasClass("open")) {
        $("#buddy_id" + pb_id).attr({'selectedIndex':0});
        $("#sendGiftForm" + pb_id).addClass("open");
        $("#sendGiftForm" + pb_id).slideDown('fast');
    }
}
function GC_showPreview(pbid) {
    // your_name greeting theme sku
    var frm = $("#gcfrm");
    var params = {
                    your_name : $("input.your_name"+pbid, frm).val(),
                    greeting : $("textarea.greeting"+pbid, frm).val(),
                    theme : $("input.theme"+pbid+":checked", frm).val(),
                    sku : $("input.sku"+pbid, frm).val()
                 }

    $.post("/giftcard-save-temp", params, function (resp) {
        //alert(resp);
        eval("var gcpop"+resp+" = window.open('/giftcard-preview?temp_id="+resp+"', 'gcpop"+resp+"', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, menubar=no, status=no, resizable=yes, width=960, height=660, top=50, left=50');");
    });
}

