﻿
(function ($) {
    $.fn.AllCheck = function (options) {
        var opts = $.extend({}, $.fn.AllCheck.defaults, options);
        return this.each(function () {
            $(this).click(function () {
                $('.' + opts.fatherElementClass).each(function (i, e) {
                    $('.' + opts.fatherElementClass).find('input').attr('checked', opts.Checked);
                    if (eval(opts.Checked)) {
                        $('.' + opts.fatherElementClass).find(opts.ClassSet).addClass(opts.classref);
                    }
                    else {
                        $('.' + opts.fatherElementClass).find(opts.ClassSet).removeClass(opts.classref);
                    }
                });
            });
        });
    };

    $.fn.AllCheck.defaults = {
        fatherElementClass: 'FriendshipListRef',
        Checked: true,
        ClassSet: 'div.item_friend',
        classref: 'bgAtivo'
    };
})(jQuery);


(function ($) {
    $.fn.Pagination = function (options) {
        var opts = $.extend({}, $.fn.Pagination.defaults, options);

        return this.each(function () {

            $(this).find('a').removeClass('active');
            $(this).find('a').each(function (i) {

                if (parseInt($(this).html()) == opts.IndexPage) {
                    $(this).addClass('active');

                }
                $(this).click(function (e) {
                    e.preventDefault();
                    opts.callMethod($(this).find('span').html());
                });


            });
        });
    };

    $.fn.Pagination.defaults = {
        callMethod: null,
        IndexPage: 0
    };

})(jQuery);


(function ($) {
    $.fn.LoadTemplate = function (options) {
        var opts = $.extend({}, $.fn.LoadTemplate.defaults, options);
        return this.each(function () {

            var target = $(this);
            $(this).empty();

            if ($.template['' + opts.TemplateName + ''] == undefined) {

                $.ajax({
                    url: opts.UrlTemplate,
                    dataType: 'get',
                    async: opts.async,
                    success: function (template) {
                        $.template('' + opts.TemplateName + '', template);
                        if (opts.Data) {
                            $.tmpl('' + opts.TemplateName + '', opts.Data).appendTo(target);

                            if (opts.IsPaging) {
                                LoadPaging(opts.DataPaging, opts.PagingTarget, opts.PagingOptions);
                            }
                        }

                        if (opts.CallMethod) {
                            if (opts.Parameters != null) {
                                opts.CallMethod(opts.Parameters);
                            }
                            else {
                                opts.CallMethod();
                            }

                        }
                    }
                });

            }
            else {
                if (opts.Data) {
                    $.tmpl('' + opts.TemplateName + '', opts.Data).appendTo(target);
                    if (opts.IsPaging) {
                        LoadPaging(opts.DataPaging, opts.PagingTarget, opts.PagingOptions);
                    }
                }

                if (opts.CallMethod) {
                    if (opts.Parameters != null) {
                        opts.CallMethod(opts.Parameters);
                    }
                    else {
                        opts.CallMethod();
                    }
                }
            }
        });
    };

    //váriaveis default	
    $.fn.LoadTemplate.defaults =
	{
	    Data: null,
	    TemplateName: '',
	    UrlTemplate: '',
	    CallMethod: null,
	    Parameters: null,
	    DataPaging: null,
	    IsPaging: false,
	    PagingOptions: null,
	    PagingTarget: null,
	    async: true
	};


    /* métodos privados  */

})(jQuery);

function LoadPaging(object, PagingTarget, optionsPaging) {
    $(PagingTarget).empty();

    if ($.template['tmpGenericPaging'] == undefined) {
        $.get('/AsyncTemplate/Paging/GenericPaging.htm', function (templatePaging) {
            $.template("tmpGenericPaging", templatePaging);
            $.tmpl("tmpGenericPaging", object).appendTo(PagingTarget);
            $(PagingTarget).find('ul').Pagination(optionsPaging);
        });
    }
    else {
        $.tmpl("tmpGenericPaging", object).appendTo(PagingTarget);
        $(PagingTarget).find('ul').Pagination(optionsPaging);
    }
}

function buildPaginationData(pTotal, pPageSkip, pPageSize) {
    var p = {};
    p.Pages = new Array();

    var pages = Math.ceil(pTotal / pPageSize);

    for (var x = 0; x < pages; x++) {
        p.Pages[x] = (x + 1);
    }

    p.PageIndex = Math.round(Math.ceil(pPageSkip / pPageSize)) + 1;
    p.RowsCount = pTotal;
    p.PageSize = pPageSize;

    return p;
}


function copy(str) {
    document.clipboardData.setData('Text', str);
}


function showPopupImage(pUrl, pTitle) {
    $.fancybox(
		    {
		        'title': pTitle,
		        'href': pUrl,
		        'showCloseButton': true,
		        'autoDimensions': true,
		        'centerOnScroll': true,
		        'scrolling': 'no',
		        'transitionIn': 'elastic',
		        'transitionOut': 'elastic',
		        'easingIn': 'easeOutBack',
		        'easingOut': 'easeInBack',
		        'opacity': true
		    }
	    );
}

function showMessage(pMessage, pAutoClose) {

    $('.customMessage').html(pMessage);

    $.fancybox({
        'autoScale': false,
        'transitionIn': 'none',
        'transitionOut': 'none',
        'width': 200,
        'height': 200,
        'href': '#modal_message',
        'onComplete': function () {
            if (pAutoClose) {
                setTimeout('$.fancybox.close()', 4000);
            }
        }
    });
}

function showMessageCall(pTitle, pMessage, pIcon, pAutoClose) {

    //    $('#modal_message .title').html(pTitle);
    //    $('#modal_message .message').html(pMessage);
    //    $('#modal_message').addClass(pIcon);

    $('.customMessage').html(pMessage);

    $.fancybox({
        'autoScale': false,
        'transitionIn': 'none',
        'transitionOut': 'none',
        'href': '#modal_message',
        'onComplete': function () {
            if (pAutoClose) {
                setTimeout('$.fancybox.close()', 4000);
            }
        }
    });

}

function showMessageCallBack(pTitle, pMessage, pIcon, pAutoClose, pCallBack) {

    //    $('#modal_message .title').html(pTitle);
    //    $('#modal_message .message').html(pMessage);
    //    $('#modal_message').addClass(pIcon);
    $('.customMessage').html(pMessage);

    $.fancybox({
        'autoScale': false,
        'transitionIn': 'none',
        'transitionOut': 'none',
        'href': '#modal_message',
        'onComplete': function () {
            if (pAutoClose) {
                setTimeout('$.fancybox.close()', 4000);
            }
        },
        'onClosed': function () {
            if (pCallBack) {
                pCallBack();
            }
        }
    });
}


function showHtmlPopup(pTitle, pMessage, pWidth, pHeight, pCustomPage, pOnClosedJavascript) {
    pMessage = '<strong>Mensagem:</strong><br /><br />' + pMessage;

    if (pCustomPage == '') {
        $.fancybox(
		    pMessage,
		    {
		        'width': '200',
		        'height': '100',
		        'title': pTitle,
		        'showCloseButton': true,
		        'autoDimensions': true,
		        'centerOnScroll': true,
		        'scrolling': 'no',
		        'transitionIn': 'elastic',
		        'transitionOut': 'elastic',
		        'easingIn': 'easeOutBack',
		        'easingOut': 'easeInBack',
		        'opacity': true,
		        onClosed: function () {
		            if (pOnClosedJavascript != '') {
		                eval(pOnClosedJavascript);
		            }
		        }
		    }
	    );
    }
    else {
        $.fancybox(
		    {
		        'width': parseInt(pWidth),
		        'height': parseInt(pHeight),
		        'title': pTitle,
		        'centerOnScroll': true,
		        'transitionIn': 'elastic',
		        'transitionOut': 'elastic',
		        'easingIn': 'easeOutBack',
		        'easingOut': 'easeInBack',
		        'type': 'iframe',
		        'href': pCustomPage,
		        'opacity': true,
		        onClosed: function () {
		            if (pOnClosedJavascript != '') {
		                eval(pOnClosedJavascript);
		            }
		        }
		    }
	    );
    }
}

function validateEmail(email) {
    var emailPattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (email == "" || !emailPattern.test(email)) {
        ModalBox.Show({ Title: "Email Inválido.", Width: 300, Error: true });
        return false;
    }
    return true;
}

function validateUrl(url) {
    var validUrl = new RegExp('^(http|https|ftp)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&amp;%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&amp;%\$#\=~_\-]+))*$');
    if (url == "" || !validUrl.test(url)) {
        ModalBox.Show({ Title: "Url inválida.", Width: 300, Error: true });
        return false;
    }
    return true;
}


function ConfirmMessage(pCustumMessage, callMethodReferece) {

    $('#customMessage').html(pCustumMessage);

    $('#btnYes').click(function () {
        callMethodReferece();
        $.fancybox.close();

        return false;
    });
    $.fancybox({
        'autoScale': false,
        'transitionIn': 'none',
        'transitionOut': 'none',
        'href': '#ConfirmMessageReferece'
    });
}

function deletaLI(object) {
    $(object).parents("li").each(function (e) {
        if (e < 1) {
            $(this).css({
                overflow: "hidden"
            }).animate({
                height: 0
            }, 500, function () {
                $(this).remove();
            })
        }
    });
}


function ConfirmMessageParameters(pCustumMessage, callMethodReferece, Parameters, object) {

    $('.customMessage').html(pCustumMessage);

    $('#btnYes').click(function () {
        if (object) {
            eval(callMethodReferece(Parameters, object));
        }
        else {
            eval(callMethodReferece(Parameters));
        }
        $.fancybox.close();
    });
    $.fancybox({
        'autoScale': false,
        'transitionIn': 'none',
        'transitionOut': 'none',
        'href': '#ConfirmMessageReferece'
    });
}

function callServerMethod(pServerMethodAddress, pSuccessCallback) {
    callServerMethod(pServerMethodAddress, pSuccessCallback, null);
}

var lastRequestCacheDate = new Date().getTime();
var lastRequestCacheDateArray = new Array();

function clearRequestCache() {
    lastRequestCacheDate = new Date().getTime();
}

function callServerMethod(pServerMethodAddress, pSuccessCallback, pCallerReference) {
    $.ajax({
        type: "GET",
        url: pServerMethodAddress,
        contentType: "application/json; charset=utf-8",
        data: '{}',
        cache: (lastRequestCacheDate == null || lastRequestCacheDateArray[pServerMethodAddress] == lastRequestCacheDate) ? true : false,
        dataType: "json",
        success: function (data) { pSuccessCallback(data, pCallerReference) },
        error: function (data) { defaultFailureCallback(data); }
    });

    lastRequestCacheDateArray[pServerMethodAddress] = lastRequestCacheDate;
}

function callServerMethodByPost(pServerMethodAddress, pData, pSuccessCallback, pExtraArgument) {
    $.ajax({
        type: "POST",
        url: pServerMethodAddress,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(pData),
        dataType: "json",
        processData: false,
        success: function (data) { pSuccessCallback(data, pExtraArgument) },
        error: function (data) { defaultFailureCallback(data); }
    });
}

var defaultFailureCallback = function (result) {
    LogFailure(result.status, document.location, result.statusText);
    //    alert(result.status + ' ' + result.statusText);
}

function SetEvent(obj, callMethod) {
    $(obj).keydown(function (e) {
        var keyCode = e.keyCode;
        if (keyCode == 13) {
            e.preventDefault();
            callMethod();
        }
    });
}

function SetEventParam(obj, callMethod) {
    $(obj).keydown(function (e) {
        var keyCode = e.keyCode;
        if (keyCode == 13) {
            e.preventDefault();
            var buttonEvent = $(obj).parents('fieldset').find('input:eq(1)');
            callMethod(buttonEvent);
        }
    });
}

function bindDataInTemplate(pTemplateName, pAjaxResult, pSelector) {
    if (pAjaxResult.ErrorMessage == null) {
        $(pSelector).empty();
        $.tmpl(pTemplateName, pAjaxResult.Entity).appendTo(pSelector);

        loadLikeIconList();
    }
    else {
        alert('Ocorreu um erro: ' + pAjaxResult.ErrorMessage);
    }
}

function disableLink(pElement, pTooltipMessage) {
    if (!pElement.hasClass('disabled')) {
        pElement.addClass('disabled');
    }

    pElement.attr('title', pTooltipMessage);
    pElement.removeAttr('href');
}

function getFormattedCurrentDateTime() {
    var d = new Date();

    return d.getDay() + '/' + d.getMonth() + '/' + d.getFullYear() + ' | ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds()
}

function getCurrentMonthLiteral() {
    var currentDate = new Date();
    var currentMonth = currentDate.getMonth();

    if (currentMonth == 1) {
        return 'Jan';
    }
    else if (currentMonth == 2) {
        return 'Fev';
    }
    else if (currentMonth == 3) {
        return 'Mar';
    }
    else if (currentMonth == 4) {
        return 'Abr';
    }
    else if (currentMonth == 5) {
        return 'Mai';
    }
    else if (currentMonth == 6) {
        return 'Jun';
    }
    else if (currentMonth == 7) {
        return 'Jul';
    }
    else if (currentMonth == 8) {
        return 'Ago';
    }
    else if (currentMonth == 9) {
        return 'Set';
    }
    else if (currentMonth == 10) {
        return 'Out';
    }
    else if (currentMonth == 11) {
        return 'Nov';
    }
    else {
        return 'Dez';
    }
}

function loadTemplateResult(pTemplateUrl, pData, pTemplateResultCallback) {
    if ($.template[pTemplateUrl] == undefined) {
        $.get(pTemplateUrl, function (template) {
            $.template(pTemplateUrl, template);
            pTemplateResultCallback($.tmpl(pTemplateUrl, pData));
        });
    }
    else {
        pTemplateResultCallback($.tmpl(pTemplateUrl, pData));
    }
}

function getNullableStringParameter(pParameter) {
    return (pParameter == null || $.trim(pParameter) == '') ? null : pParameter;
}

String.prototype.format = function () {
    var pattern = /\{\d+\}/g;
    var args = arguments;
    return this.replace(pattern, function (capture) { return args[capture.match(/\d+/)]; });
}

String.prototype.startsWith = function (prefix) {
    return this.indexOf(prefix) === 0;
}

function getPreviewVideoUrl(pVideoUrl) {
    var videoUrl = pVideoUrl;

    if (pVideoUrl.indexOf('www.youtube.com/embed/') > -1) {
        videoUrl += '&controls=0';
    }

    return videoUrl;
}

function AddTag(pArea, pTitle, pBehavior) {
    javascript: _gaq.push(['_trackEvent', '' + pArea + '', '' + pTitle + '', '' + pBehavior + '']);
}

function LoadHour(objSelected) {
    for (var x = 0; x <= 23; x++) {
        var h = (x <= 9) ? "0" + x : x;
        $(objSelected).append('<option value=\"' + h + '\">' + h + '</option>');
    }
}

function LoadMinutes(objSelected) {
    for (var x = 0; x <= 59; x++) {
        var h = (x <= 9) ? "0" + x : x;
        $(objSelected).append('<option value=\"' + h + '\">' + h + '</option>');
    }
}
function CopyToClipboard(text) {
    window.clipboardData.setData("Text", text);
    if (window.clipboardData) {

    }
}

function dateMask(inputData, e) {
    if (document.all) // Internet Explorer
        var tecla = event.keyCode;
    else //Outros Browsers
        var tecla = e.which;

    if (tecla >= 47 && tecla < 58) { // numeros de 0 a 9 e "/"
        var data = inputData.value;
        if (data.length == 2 || data.length == 5) {
            data += '/';
            inputData.value = data;
        }
    } else if (tecla == 8 || tecla == 0) // Backspace, Delete e setas direcionais(para mover o cursor, apenas para FF)
        return true;
    else
        return false;
}


function isDate(valor) {
    var date = valor;
    var ardt = new Array;
    var ExpReg = new RegExp('(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/[12][0-9]{3}');
    ardt = date.split("/");
    erro = false;
    if (date.search(ExpReg) == -1) {
        erro = true;
    }
    else if (((ardt[1] == 4) || (ardt[1] == 6) || (ardt[1] == 9) || (ardt[1] == 11)) && (ardt[0] > 30))
        erro = true;
    else if (ardt[1] == 2) {
        if ((ardt[0] > 28) && ((ardt[2] % 4) != 0))
            erro = true;
        if ((ardt[0] > 29) && ((ardt[2] % 4) == 0))
            erro = true;
    }
    if (erro)
        return false;

    return true;
}


