﻿var datePickerOptions = { showOn: "both", buttonImage: webRoot + '/_i/ui/btn_calendar.gif', buttonImageOnly: true, showAnim: "slideDown", prevText: ' ', nextText: ' ', yearRange: '-90:0' };
var dateTimePickerOptions = { dateFormat: "dd.mm.yy", showOn: "both", buttonImage: webRoot + '/_i/ui/btn_calendar.gif', buttonImageOnly: true, showAnim: "slideDown", showTime: true, timePos: "top" };

// MagiClick Javascript Framework v0.1
// some routines dropped from prototype.js ;)
// Author: Omerz
var MinDate = Date.parse("01.01.0001 00:00:00");
var _alert = null, _alertBoxIndex = 0, _alertBoxVisibleCount = 0;
var EnableClientDebugging = false;
function debug(debDetails) {
    if (EnableClientDebugging && $.browser.msie) {
        console.log(debDetails)
    }
}

Array.prototype.indexOf = Array.prototype.indexOf || function(_value) {
    var index = -1;
    for (var i = 0; i < this.length; i++)
        if (this[i] == _value) {
        index = i;
        break;
    }
    return index;
};

jQuery.fn.extend({
    scrollTo: function(speed, easing) {
        return this.each(function() {
            var targetOffset = $(this).offset().top;
            $('html,body').animate({ scrollTop: targetOffset }, speed, easing);
        });
    }
});

$.preloadImages = function(args) {
    if ((typeof args) == "string") {
        var preImg = new Image();
        preImg.src = args;
    } else if ((typeof args) == "object") {
        for (var x = 0; x < args.length; x++) {
            var preImg = new Image();
            preImg.src = args[x];
            /*preImg.onload=function(){
            console.log("Image " + this.src + " preloaded");
            };*/
        }
    }
}

$.preloadImage = function(imageSrc, callback) {
    var preImg = new Image();
    if (callback != null) {
        preImg.onload = function(evt) {
            callback(evt);
        };
    }
    preImg.src = imageSrc;
};

// overriding browsers' default alert
function overrideAlert() {
    _alert = window.alert;
    var srcAlertBox = $("#alertBox");
    var tarAlertBoxes = $("#alertBoxes");
    var alertBgMask = $("#alertBox_bgmask");
    var zStarter = 980;

    $.preloadImages(['_i/popup_r1_c1.gif', '_i/popup_r1_c2.gif', '_i/popup_r1_c3.gif', '_i/popup_r2_c1.gif', '_i/popup_r2_c3.gif', '_i/popup_r3_c1.gif', '_i/popup_r3_c2.gif', '_i/popup_r3_c3.gif']);

    window.alert = function(strAlertMsg, strMsgTitle, closeHandler, styles) {
        if (strMsgTitle == null)
            strMsgTitle = "Uyarı";

        if ((typeof strAlertMsg) == "string" && !strAlertMsg.isHtml()) {
            strAlertMsg = strAlertMsg.replace(/\r\n/g, "<br/>");
            strAlertMsg = strAlertMsg.replace(/\r/g, "<br/>");
            strAlertMsg = strAlertMsg.replace(/\n/g, "<br/>");
        }

        // Create new instance of alertBox
        var strNewID = "alert" + _alertBoxIndex;
        var strAlertHtml = srcAlertBox.html();
        strAlertHtml = strAlertHtml.replace(/id_replacement/g, strNewID);
        tarAlertBoxes.append(strAlertHtml);

        var strCreatedBox = "#" + strNewID + "_box";
        var createdBox = $(strCreatedBox);
        var createdBox_title = $(strCreatedBox + "_title");
        var createdBox_content = $(strCreatedBox + "_content");

        createdBox[0].Close = function() {
            _alertBoxVisibleCount--;
            $(this).remove();
            if (_alertBoxVisibleCount <= 0) {
                alertBgMask.css("display", "none");
                _alertBoxVisibleCount = 0;
                window.onscroll = function() { };
            }

            if (closeHandler != null)
                closeHandler();
        };

        // disable text selections both of moz and ie
        createdBox[0].onselectstart = function(e) {
            return false;
        };
        createdBox.css("-moz-user-select", "none");

        createdBox_title.text(strMsgTitle);
        createdBox_content.html(strAlertMsg);

        // set min width
        if (createdBox.width() < 300) {
            createdBox.find("table").width(300);
        }


        //set box to center of the screen
        var newPosx = ($(window).width() / 2) - (createdBox.width() / 2); // - $(document).scrollLeft();
        var newPosy = ($(window).height() / 2) - (createdBox.height() / 2); // - $(document).scrollTop();

        if (_alertBoxVisibleCount > 0) {
            newPosx += (10 * _alertBoxVisibleCount);
            newPosy += (10 * _alertBoxVisibleCount);
        }

        createdBox.css("left", newPosx);
        createdBox.css("top", newPosy);

        createdBox.draggable({ handle: '.handler' });

        if ($.browser.msie && ($.browser.version.indexOf("6.") > -1 ? true : false)) {
            alertBgMask.height($(document).height());
            createdBox.css("top", $(document).scrollTop() + newPosy);
            window.onscroll = function(evt) {
                createdBox.css("top", $(document).scrollTop() + newPosy);
            };
        }

        // setting up Z order 
        createdBox.css("zIndex", _alertBoxIndex + zStarter);
        if (_alertBoxVisibleCount <= 0) {
            alertBgMask.css("display", "block");
            alertBgMask.css("zIndex", _alertBoxIndex + zStarter - 1);
        }
        createdBox.css("display", "block");

        _alertBoxIndex++;
        _alertBoxVisibleCount++;
        return createdBox;
    }
}

function CloseActiveAlert() {
    var alertBoxes = $("div[id^=alert].tblPopup");
    alertBoxes[alertBoxes.length - 1].Close();
    return true;
}

function CloseAlert(intIndex) {
    var alertBoxes = $("div[id^=alert].tblPopup");
    if (intIndex >= alertBoxes.length) return false;
    alertBoxes[intIndex].Close();
}

function setLoading(strTarget, message) {
    var targetObj = $(strTarget);
    if (targetObj.css("display") == "none")
        return;
    if (targetObj.length <= 0)
        return;

    var strHtmlLoading = $("#ajaxLoader").html();
    var strLoaderID = targetObj[0].id + "_loader";
    var strLoaderPrgID = targetObj[0].id + "_loader_prg";
    var strLoaderMsgID = targetObj[0].id + "_loader_msg";
    var strContentID = targetObj[0].id + "_content";

    // if loader not removed or already created?
    if ($("#" + strLoaderID).length > 0)
        return;

    strHtmlLoading = strHtmlLoading.replace(/id_replacement/i, strLoaderID);
    strHtmlLoading = strHtmlLoading.replace(/id_replacement_prg/i, strLoaderPrgID);
    strHtmlLoading = strHtmlLoading.replace(/id_replacement_msg/i, strLoaderMsgID);

    // append loader data top of the target object.
    targetObj.before(strHtmlLoading);
    //targetObj.parent().prepend(strHtmlLoading);

    var objLoader = $("#" + strLoaderID);
    objLoader.width(targetObj.width());
    if (targetObj.height() > 100) {
        objLoader.height(targetObj.height());

        $("#" + strLoaderPrgID).css("margin-top", (targetObj.height() / 2) - $("#" + strLoaderPrgID).height());
    }

    if (message != null)
        $('#' + strLoaderMsgID).text(message);
    objLoader.show();
}

function resetLoading(strTarget) {
    var targetObj = $(strTarget);
    if (targetObj.length <= 0)
        return;
    var objLoader = $("#" + targetObj[0].id + "_loader");
    if (objLoader.length <= 0)
        return;

    objLoader.remove();

}



function showPageLoader() {
    $("#loaderLayer").show();
    if ($.browser.msie && ($.browser.version.indexOf("6.") > -1 ? true : false)) {
        $("#loaderLayer").height($(document).height());
    }
}

function hidePageLoader() {
    $("#loaderLayer").hide();
}

// Text evaulation routines
function EvalBoolean(o) {
    if (o == null) {
        return "<img src=\"_i/icon_2.gif\" alt=\"\"/>";
    } else {
        switch (typeof o) {
            case 'string':
                if (o == "E" || o == "1")
                    return "<img src=\"_i/icon_1.gif\" alt=\"\" align=\"absmiddle\"/> Evet";
                else
                    return "<img src=\"_i/icon_2.gif\" alt=\"\" align=\"absmiddle\"/> Hayır";
                break;
            case 'number':
                if (o == 1)
                    return "<img src=\"_i/icon_1.gif\" alt=\"\" align=\"absmiddle\"/>";
                else
                    return "<img src=\"_i/icon_2.gif\" alt=\"\" align=\"absmiddle\"/>";
                break;
            case 'boolean':
                if (o)
                    return "<img src=\"_i/icon_1.gif\" alt=\"\" align=\"absmiddle\"/>";
                else
                    return "<img src=\"_i/icon_2.gif\" alt=\"\" align=\"absmiddle\"/>";
                break;
        }
    }
    return null;
}

function EvalNull(o) {
    if (o == null) {
        return "<img src=\"_i/icon_3.gif\" alt=\"\" />";
    }
    else {
        switch (typeof o) {
            case 'number':
                if (o > 0)
                    return o;
                else
                    return "<img src=\"_i/icon_3.gif\" alt=\"\" align=\"absmiddle\" />";
                break;
            case 'string':
                if (o.length == 0)
                    return "<img src=\"_i/icon_3.gif\" alt=\"\" />";
                break;
        }
    }
    return o;
}

function EvalDate(o, format) {
    if (format == null)
        format = "dd.MM.yyyy";
    if (typeof o == 'string') {
        if (o.substring(o.length - 1) == "Z")
            o = o.substring(0, o.length - 1);
        o = Date.parse(o);
    }

    if (o == null)
        return null;
    if (o._orient != null && o._is != null) {
        //if (MinDate.equals(o)) return null;
        return o.toString(format);
    } else {
        return null;
    }
}

function EvalFileExt(o) {
    if (o == null)
        return null;
    var dotPos = o.lastIndexOf(".");
    if (dotPos <= 0) return null;
    dotPos++;
    var strExt = o.substring(dotPos, o.length);
    return strExt;
}

function EvalFileExtIcon(o) {
    if (o == null)
        return null;
    var strExt = EvalFileExt(o);
    return "<img src=\"_i/icons/ico_" + strExt + ".png\" alt=\"\" align=\"absmiddle\" />";
}

function SetStateCookie(_id, _root, _state) {
    var date = new Date();
    date.setTime(date.getTime() + (365 * 2 * 3 * 24 * 60 * 60 * 1000));
    $.cookie("state_" + _id, _state, _root, { expires: date });
}

function GetStateCookie(_id, _root) {
    return $.cookie("state_" + _id);
}

function lookupRecord(intRecID, dataSource, equals) {
    if (dataSource == null)
        return null;
    // lookup record in loaded records
    var x;
    for (var x = 0; x < dataSource.length; x++) {
        if (eval("dataSource[x]." + equals + "==intRecID")) {
            return { record: dataSource[x], index: x };
        }
    }
}

function lookupRecords(intRecID, dataSource, equals) {
    var resultset = new Array();
    if (dataSource == null)
        return null;
    // lookup record in loaded records
    var x;
    for (var x = 0; x < dataSource.length; x++) {
        if (eval("dataSource[x]." + equals + "==intRecID")) {
            resultset.push(dataSource[x]);
        }
    }
    return resultset;
}

function onlyLetter(e) {
    var InvalidChars = "!#/*{[()]},;%^><\\?+:='`|é&æ~£$½¨ß";

    var keyCode = ($.browser.mozilla) ? e.which : event.keyCode;

    if (keyCode > 47 && keyCode < 58) {
        return false;
    }
    for (i = 0; i <= InvalidChars.length - 1; i++) {
        if (keyCode == InvalidChars.charCodeAt(i)) {
            return false;
        }
    }
}


function onlyNumber(e) {
    var keyCode = ($.browser.mozilla) ? e.which : event.keyCode;
    if ((keyCode < 48 || keyCode > 57) && keyCode != 8 && keyCode != 0) {
        return false;
    }
}

function onlyTelNumber(sender) {

    if (sender.value != "" && !isTelNumberValid(sender.value)) {
        alert("Girdiğiniz Telefon Numarası hatalıdır. Lütfen kontrol ediniz");
        sender.value = "";
        return false;
    }
}

function isTelNumberValid(value) {
    var exp = new RegExp(/^([0-9]{3}\s{0,1}[0-9]{2}\s{0,1}[0-9]{2})$/);
    var match = exp.exec(value);
    return (match != null);
}

function onlyEmail(e) {
    var InvalidChars = " !#/*{[()]},;%^><\\?+:='`|şŞĞğÜüÇçİıÖö";

    kCode = InvalidChars.charAt(5);

    var keyCode = ($.browser.mozilla) ? e.which : event.keyCode;

    if (keyCode > 127) {
        return false;
    }
    for (i = 0; i <= InvalidChars.length - 1; i++) {
        if (keyCode == InvalidChars.charCodeAt(i)) {
            return false;
        }
    }
    return true;
}

function gotoUrl() { //based on mm_goToURL
    for (var i = 0; i < (gotoUrl.arguments.length - 1); i += 2)
    //with arg pairs
        eval(gotoUrl.arguments[i] + ".location='" + gotoUrl.arguments[i + 1] + "'");
    //document.MM_returnValue = false;
}

function initTabs() {
    $(".tabControl a").eq(0).addClass("selected");
    $(".tabContent .tabContentItem").eq(0).addClass("active");
    $(".tabControl a").click(function() {
        $(".tabControl a").removeClass("selected");
        $(".tabContent .tabContentItem").removeClass("active");
        $(this).addClass("selected");
        var _index = $(".tabControl a").index(this);
        $(".tabContent .tabContentItem").eq(_index).addClass("active");
        $(this).trigger('tabchange');
        //console.log(this);
        return false;
    });
}

$.ajaxNavigations = function(defaultView) {
    /* Ajax navigation init */
    $.history.init(function(hash, src) {
        var hashBreaked = false;
        function switchPanels(newHash) {
            var obj2Hide = $('div.panel:not(.hidden):not(#' + newHash + ')');
            var canShow = null;
            obj2Hide.each(function() {
                var obj2Hide_ret = $.event.trigger('hide', [src], this, true, null);
                if (canShow == null) {
                    if (obj2Hide_ret == false) {
                        canShow = false;
                        return false;
                    }
                }
                //console.log(obj2Hide_ret);
            });
            if (canShow != false) {
                obj2Hide.addClass('hidden');
                $('div#' + newHash + '.panel').removeClass('hidden').trigger('show', [src]);
            }
            return (canShow != false);
        }
        // hash doesn't contain the first # character.
        if (hash) {
            // sublinks?
            var directory = hash.split('/');
            //console.log(hash + " - " + directory.length);
            $.each(directory, function(x) {
                var curDir = directory[x];

                if (curDir.indexOf('view') > -1) {
                    if (!switchPanels(curDir)) {
                        hashBreaked = true;
                        return false;
                    }
                } else if (curDir.indexOf('$') > -1) {
                    curDir = curDir.replace('$', '#');
                    $('a[href=' + curDir + ']').trigger('click');
                } else {
                    if (typeof curDir != null && !hashBreaked) {
                        $('div#' + directory[x - 1] + '.panel').trigger('query', [curDir, directory[x + 1]]);
                    }
                }
            });
        } else {
            gotoUrl('parent', defaultView);
        }
        return !hashBreaked;
    });

    /*function historyLoad(hash){
    hash = hash.replace(/^.*#/, '');
    // moves to a new page.
    // pageload is called at once.
    return $.history.load(hash);
    }*/

    // set onlick event for buttons
    $("a[@rel='history']").click(function(evt) {
        console.log('history click');
        var hash = this.href;
        return $.ajaxNavigations.historyLoad(hash, evt);
    });

    $('input[ajaxAction]').bind('click', function(evt) {
        return $.ajaxNavigations.historyLoad($(this).attr('ajaxAction'), evt);
    });
    /* End of ajax navigations */
};

$.ajaxNavigations.historyLoad = function(hash, src) {
    hash = hash.replace(/^.*#/, '');
    // moves to a new page.
    // pageload is called at once.
    return $.history.load(hash, src);
};

$(document).ready(function() {
overrideAlert();
    if ($.WebServices != null) {
        $.WebServices.onError = function(err, extraDetails) {
            if (err.message = !null && err.message.indexOf("[401.2]") > -1) {
                gotoUrl('parent', 'ErisimYetkiHatasi.aspx');
            } else {
                alert("Veri alınırken hata oluştu!", "Hata");
                console.warn("$.WebServices.onError ->");
                if (extraDetails != null)
                    console.error(extraDetails);
                console.error(err.name);
                console.error(err.description);
                if ($.browser.msie) console.open();
            }
        };
    }

    if (EnableClientDebugging && $.browser.msie) {
        console.info("Magic Debugging Enabled");
        window.onerror = function(msg, url, lno) {
            alert('JavaScript hatası! <br/> Dosya :' + url + ', satır: ' + lno + ' <br/>Mesaj: ' + msg, 'JavaScript hatası!');
            //console.error("Document Error ->" + url + " at line " + lno);
            //console.error("Message:" + msg);
            //if($.browser.msie) console.open();
            return true;
        };

        $.WebServices.onBeforeCall = function(xhr, uri, soapEnv) {
            console.group("$.WebServices.onBeforeCall -> URI:" + uri);
            console.log(soapEnv);
            console.groupEnd();
            return true;
        };

        $.WebServices.onFinally = function(xhr, textStatus) {
            //console.info("$.WebServices.onFinally -> State:" + textStatus);
            console.group("$.WebServices.onFinally -> State:" + textStatus);
            console.log(xhr.responseText);
            console.groupEnd();
            //debug(xhr.responseText);
            return true;
        };
    }
    
    // JFR Definitions   
    /*jfr$('h2.maintitle').jfr({
        src:'_swf/jfr/Lucidia_Sans.swf',
        css:[
            '* { color: #ffffff; text-align: left; }',
            'a { color: #0099CC; text-decoration: none; }',
            'a:hover { text-decoration: underline; }'
            ]
    });
    
    jfr$('h2.records').jfr({
        src:'_swf/jfr/Lucidia_Sans.swf',
        css:[
            '* { color: #666666; text-align: left;}',
            'a { color: #FFCC00; text-decoration: none; }',
            'a:hover { text-decoration: underline; }'
            ]
    });
    
    jfr$('h2').jfr({
        src:'_swf/jfr/Lucidia_Sans.swf',
        css:[
            '* { color: #666666; text-align: left; }',
            'a { color: #FFCC00; text-decoration: none; }',
            'a:hover { text-decoration: underline; }'
            ]
    });
    
    jfr$('h3#loginText').jfr({
        src:'_swf/jfr/Lucidia_Sans.swf',
        css:[
            '* { color: #666666; text-align: left;  }',
            'a { color: #0099CC; text-decoration: none; }',
            'a:hover { text-decoration: underline; }'
            ]
    });
    
    jfr$('h3#LoginTitle').jfr({
        src:'_swf/jfr/Lucidia_Sans.swf',
        css:[
            '* { color: #666666; text-align: left; font-z}',
            'a { color: #0099CC; text-decoration: none; }',
            'a:hover { text-decoration: underline; }'
            ]
    });
    
    jfr$('p.tblTit').jfr({
        src:'_swf/jfr/Lucidia_Sans_Bold.swf',
        css:[
            '* { color: #666666; text-align: left; font-weight:bold; font-size:18px; }',
            'a { color: #FFCC00; text-decoration: none; }',
            'a:hover { text-decoration: underline; }'
            ]
    });*/
    
//    if(editorScriptsDefined){
//        $.clipboardReady(function(){},{ swfpath: "_swf/jquery.clipboard.swf", debug: false });
//        initTabs();
//    }
    
    $.jfr.render();
    
//    if($("#footer").length>0){
//        
//        function onResizeHandler(){
//            if($(window).height()>($("#container").outerHeight()+$("#footer").outerHeight()))
//                $("#footer").css("margin-top",$(window).height() - $("#container").outerHeight() - $("#footer").outerHeight()+ "px").css('margin-bottom','-20px');
//            else
//                $("#footer").css("margin-top","0px");
//               
//            fitViews();
//        }
//        onResizeHandler();
//        $("#footer").css("display","block");
//        window.onresize = onResizeHandler;
//    }
    
});