﻿// implements a c# style string format
String.format = function(text) {
    if (arguments.length <= 1) {
        return text;
    }
    var tokenCount = arguments.length - 2;
    for (var token = 0; token <= tokenCount; token++) {
        text = text.replace(new RegExp("\\{" + token + "\\}", "gi"), arguments[token + 1]);
    }
    return text;
};

// makes an ajaxrequest jquery style
// if dataToSend is null issues a GET, otherwise a POST
//
function getUrl(url, dataToSend, callback) {
    if (dataToSend == null) {
        jQuery.ajax({ type: 'GET',
            url: url,
            contentType: 'application/json; charset=utf-8',
            success: function(data) { callback(data); },
            dataType: "json"
        });
    }
    else {
        jQuery.post(url, dataToSend, callback, "json")
    }
}

function ShowErrorsOrReload(data) {
    if (data.status.success) {
        location.reload(true);
    }
    else {
        var errormsg = "";
        if (data.status.errors != null) {
            for (var i = 0; i < data.status.errors.length; i++) {
                if (data.status.errors[i].code != "_FORM") {
                    errormsg += data.status.errors[i].code + " - ";
                    errormsg += data.status.errors[i].desc + "\n";
                }
                else {
                    errormsg += data.status.errors[i].desc + "\n";
                }
            }
            alert(errormsg);
        }
        else {
            alert("Something went wrong!");
        }
    }
}

//PROXY FUNCTION
function isSoundOn(status){
	$.fn.isSoundOn(status);
}

$(document).ready(function(){

    //CONVERT FONT
    Cufon.replace('.convertFont', {});
    Cufon.replace('.convertFontLink', { hover: true });
    Cufon.replace('ul.menuFirstLevel li, ul.menuSecondLevel li', {
    	forceHitArea: true,
    	hover: true,
    	onAfterReplace: function()
    	{
    		//CALCULATE TOP DISTANCE FOR LIKE BUTTON
			var $mainSearch = $('.mainSearch');
			var $likeBtnTop = $mainSearch.position().top + $mainSearch.outerHeight(true) + 15;
			$('.mainLike').css({'top': $likeBtnTop});
    	}
    });

});

// used for IE hacks
function getIEVersionNumber() {
    var ua = navigator.userAgent;
    var MSIEOffset = ua.indexOf("MSIE ");
    
    if (MSIEOffset == -1) {
        return 0;
    } else {
        return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(";", MSIEOffset)));
    }
}

$(function() {

	//ADD IE VERSION TO CSS
	var ieVersion =getIEVersionNumber();
	if(ieVersion>0) {
		$("body").addClass('ie'+getIEVersionNumber())
	}

    //SHUFFLE
    // orange, purple, green, pink, aqua, blue, darkBlue, red
    var colorPalette = new Array("#fe9600", "#951cb9", "#a4d50a", "#ff6edf", "#03c0e0", "#0184df", "#00548e", "#d81e05");
    if ($(".shuffleColor").length) {
        var rand = Math.floor(Math.random() * (colorPalette.length - 1));
        $(".shuffleColor").css("color", colorPalette[rand]);
    }


    //CSS EXCEPTIONS
    $("ul.footer li:first").css({ "border-left": "none" });


    //PRINT
    $(".print a").click(function(e) {
        e.preventDefault();
        window.print();
    });


    //URL PARSE 
    $.fn.parseURL = function(url) {
        var vars = [], value;
        var url = url.split('?')[1];
        var keys = url.split('&');
        for (var i = 0; i < keys.length; i++) {
            value = keys[i].split('=');
            value[1] = decodeURI(value[1]);
            vars.push(value[0]);
            vars[value[0]] = value[1];
        }
        return vars;
    }
    //$_GET = $.fn.parseURL();


    //CHECK IF IMAGES ARE LOADED
    $.fn.imagesLoaded = function(callback) {
        var elems = this.filter('img'),
		  len = elems.length;
        elems.bind('load', function() {
            if (--len <= 0) { callback.call(elems, this); }
        }).each(function() {
            // cached images don't fire load sometimes, so we reset src.
            if (this.complete || this.complete === undefined) { this.src = this.src; }
        });
    }

    //SET EQUAL HEIGHT
    $.fn.setEqualHeight = function(o) {
        var maxHeight = 0;
        var maxElement = null;
        $(this).each(function(i) {
            var thisHeight = $(this).height();
            var paddingTop = parseInt($(this).css("padding-top"));
            var paddingBottom = parseInt($(this).css("padding-bottom"));
            if ((thisHeight + paddingTop + paddingBottom) > maxHeight) {
                maxHeight = thisHeight + paddingTop + paddingBottom;
                maxElement = this;
            }
        });
        $(this).not($(maxElement)).each(function() {
            var eachPaddingTop = parseInt($(this).css("padding-top"));
            var eachPaddingBottom = parseInt($(this).css("padding-bottom"));
            $(this).height(maxHeight - eachPaddingTop - eachPaddingBottom);
        });
    }

    //CLEAR INPUTS VALUE
    $.fn.defaultValue = function() {
        $(this).css({ "color": "#989898" });
        return $(this).each(function() {
            $(this).focus(function() {
                this.style.color = '#333333';
                if (this.value == this.defaultValue) {
                    this.value = '';
                }
                this.select();
            }).blur(function() {
                if (!$.trim(this.value)) {
                    this.value = this.defaultValue;
                    this.style.color = '#989898';
                } else {
                    this.style.color = '#333333';
                }
            }).parents("form").submit(function(e) {
                elm = $(this).find('.defaultValue')[0];
                if (elm.value == '' || elm.value == elm.defaultValue) {
                    e.preventDefault();
                } else if (this.id == 'mainSearch') {
                    e.preventDefault();
                    location.href = $(this).attr('action') + '/?search=' + encodeURIComponent(elm.value);
                }
            });
        });
    };
    $(".defaultValue").defaultValue();


    //CONFIRM BOX
    $.fn.confirmBox = function(question, message, saveCallback, cancelCallback, onShowCallback) {
        $('#confirm').modal({
            //closeHTML:"<a href='#' title='Close' class='modal-close'>x</a>",
            position: ["20%"],
            opacity: 75,
            overlayId: 'modal-overlay',
            containerId: 'confirm-container',
            onShow: function(dialog) {
                $('.question', dialog.data[0]).append(question);
                Cufon.replace('.jqmConfirmTitle');
                $('.message', dialog.data[0]).append(message);
                $('.confirm_ok').click(function(e) {
                    e.preventDefault();
                    if (typeof saveCallback == 'function') {
                        saveCallback();
                    }
                    $.modal.close();
                });
                $('.confirm_cancel').click(function(e) {
                    e.preventDefault();
                    if (typeof cancelCallback == 'function') {
                        cancelCallback();
                    }
                    $.modal.close();
                });
                if (typeof onShowCallback == 'function') {
                    onShowCallback();
                }
            }
        });
        $("#confirm-container").css("height", "auto");
    }

    //ALERT BOX
    $.fn.alertBox = function(message, callback) {
        $('#alertBox').modal({
            //closeHTML:"<a href='#' title='Close' class='modal-close'>x</a>",
            position: ["20%"],
            opacity: 75,
            escClose: true,
            overlayId: 'modal-overlay',
            containerId: 'alertBox-container',
            onShow: function(dialog) {
        		Cufon.replace('.jqmConfirmTitle');
                $('.message', dialog.data[0]).append(message);
                $('.confirm_ok').click(function(e) {
                    e.preventDefault();
                    if (typeof callback == 'function') {
                        callback();
                    }
                    $.modal.close();
                });
            }
        });
        $("#alertBox-container").css("height", "auto");
    }


    //SELECT BOX'S
    if ($(".selectBoxHTMLContainer").length) {
        $(".selectBoxHTML").hide();
        $(".selectBoxHTMLContainer").each(function() {
            if ($(this).find("option:selected")) {
                var newUL = '<input type="text" name="' + $(this).find(".selectBoxHTML").attr("name") + '" id="' + $(this).find(".selectBoxHTML").attr("id") + '" class="selectBox" readonly="readonly" value="' + $(this).find("option:selected").text() + '" title="' + $(this).find("option:selected").text() + '" />';
            } else {
                var newUL = '<input type="text" name="' + $(this).find(".selectBoxHTML").attr("name") + '" id="' + $(this).find(".selectBoxHTML").attr("id") + '" class="selectBox" readonly="readonly" value="' + $(this).find("option:eq(0)").text() + '" title="' + $(this).find("option:eq(0)").text() + '" />';
            }
            newUL += '<ul class="selectOptions">';
            $(this).find(".selectBoxHTML option").each(function() {
                newUL += '<li><a href="#" title="' + $(this).val() + '">' + $(this).text() + '</a></li>';
            });
            newUL += '</ul>';

            var grabOnchangeEvent = $(this).find(".selectBoxHTML").attr("onchange");

            $(this).html(newUL);
            $(this).find(".selectBoxHTML").remove();

            $(this).find(".selectOptions").hide();
            $(this).find(".selectBox").focus(function() {
                $(this).next("ul.selectOptions").slideDown("fast");
            });

            $(this).find(".selectBox").blur(function() {
                var ul = $(this).next("ul.selectOptions");
                setTimeout(function() { ul.slideUp("fast"); }, 100);
            });

            $(this).find("ul.selectOptions li a").click(function() {
                $(this).closest(".selectBoxHTMLContainer").find("input.selectBox").val($(this).text()).attr("title", $(this).attr("title")).attr("onchange", grabOnchangeEvent);
                return false;
            });
        });
    };


    //COMMENTS
    $.fn.Vote = function(url, stars) {
        getUrl(url + '?' + 'stars=' + stars, '', null);
    }
    $.fn.EditPost = function(url, userId, commentId) {
        getUrl(url + '?' + 'commentId=' + commentId + '&userId=' + userId, '', $.fn.PopulateCommentDialog);
    }
    $.fn.PopulateCommentDialog = function(data) {
        if (data != undefined && data.status.success == true) {
            $(".leaveComment").slideDown(function() {
                $('#Text').focus();
            });
            $('#Text').val(data.bodydata.Text);
            $('#ShowEmail').attr('checked', data.bodydata.ShowEmail);
            $('#ReceiveWarnings').attr('checked', data.bodydata.ReceiveWarnings);
            $('#CommentId').val(data.bodydata.CommentId);

        } else {
            alert("Erro!");
        }
    }
    $.fn.DeletePost = function(url, userId, commentId) {
        if (confirm(localizedStrings["Global_DeleteComment"])) {
            getUrl(url + '?' + 'commentId=' + commentId + '&userId=' + userId, '', ShowErrorsOrReload);
        }
    }
    if ($(".leaveComment").length) {
        $(".leaveComment").hide();
        $("a.commentBtn").click(function(e) {
            if (!$(this).is(".getLogin")) {
                e.preventDefault();
                $(".leaveComment").slideToggle(function() {
                    $("a.commentBtn").toggleClass("closeCommentBtn");
                    $('#Text').focus();
                });
            }
        });
    }
    $("form[name='leaveComment']").submit(function(e) {
        e.preventDefault();
        $(this).unbind('submit', function(e){ e.preventDefault(); });
        var textBoxDefaultValue = $(this).find("textarea").val();
        var jsonStr = "{ Text:'" + textBoxDefaultValue + "', ShowEmail:'" + $('#ShowEmail').attr('checked') + "', ReceiveWarnings:'" + $('#ReceiveWarnings').attr('checked') + "', CommentId:'" + $('#CommentId').val() + "' }";
        if (textBoxDefaultValue != localizedStrings["Global_WriteYourComment"] && textBoxDefaultValue != "") {
	        getUrl($("form[name='leaveComment']").attr("action"), jsonStr, function(data) {
	            if (data != undefined && data.status.success == true) {
	                $("form[name='leaveComment']").hide();
	                $(".commentSuccess").show();
	            }
	        });
        } else {
        	$.fn.alertBox(
	            localizedStrings["Global_WriteCommentPlease"],
	            function() { /*do nothing*/ }
            );
        }
    });
    
    
    //KIDSTORE GATEWAY BG
    var $gatewayKidstore = $(".gatewayKidstore");
	if($gatewayKidstore.length)
	{
		//number between 1 and 10
		var $randomBG = Math.round(Math.random () * 9 + 1);
		$gatewayKidstore.find('#contentContainer').css({'background': 'url(../images/gateway/kidstore_bg_'+ $randomBG +'.jpg) no-repeat 250px 150px'})
	}	

});
