﻿var IO_PageLoadTimeOut = null;
$.ajaxSetup({ cache: false });

function IO_OpenVideoHelp(key, title) {
    IO_DialogOpen('ifns:/Help/' + key.split('.')[0] + '/Video/ShowVideo.aspx?' + key, title, 602, 477, 'Default', true);
}

function IO_AddStyleToHeader(path, retry) {
//    $("head > link").each(function () { if ($(this).attr('href') == path) return; });
//    $("head").append('<link rel="stylesheet" href="' + path + '" type="text/css" />');

//    if (!retry && $.browser.msie && navigator.appVersion.indexOf('MSIE 6.0') > -1) {
//        window.setTimeout("IO_AddStyleToHeader('" + path + "', true);", 1000);
//    }

    var fileref = document.createElement("link")
    fileref.setAttribute("rel", "stylesheet")
    fileref.setAttribute("type", "text/css")
    fileref.setAttribute("href", path)

    if (typeof fileref != "undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
}

function IO_ToolTipShow(elm) {
    JT_show(elm, 250);
}

function IO_ToolTipHide(elm) {
    if ($(elm).attr('_title') != undefined) {
        $(elm).attr('title', $(elm).attr('_title'));
        $(elm).removeAttr('_title');
    }
    $('#JT').remove();
}

function IO_DisableEnableForm(formID, how) {
    if (document.getElementById(formID)) {
        objElems = document.getElementById(formID).elements;
        for (i = 0; i < objElems.length; i++) {
            objElems[i].disabled = how;
        }
    }
}

function IO_PrintElementContent(elmId) {
    var printWindow = window.open('', '', 'left=0,top=0,width=1,height=1,toolbar=0,scrollbars=0,status=0');

    $("head > link").each(function () {
        printWindow.document.write('<link href="' + $(this).attr('href') + '" rel="stylesheet" type="text/css" />');
    });

    printWindow.document.write($("#" + elmId).html());
    printWindow.focus();
    printWindow.print();
    printWindow.close();
}

function IO_FixContentAnchors(frame) {
    var hrefs = $(frame).get(0).contentWindow.document.getElementsByTagName('a');
    for (i = 0; i < hrefs.length; i++) {
        if ($(frame).get(0).contentWindow.document.location.toString().split('?')[1] == hrefs.item(i).name) {
            var fromTop = $(hrefs.item(i)).position().top;
            if ($.browser.mozilla) fromTop -= 20;
            $(frame).get(0).contentWindow.setTimeout("window.scrollTo(0," + fromTop + ");", 1);
        }
    }
}

function IO_AjaxPost(url, data, divid, loader) {
    $("#" + divid).html(loader);
    $.post(url, data, function (rData) {
        $("#" + divid).html(rData);
    });
}

function IO_AjaxLoad(url, divid, loader) {
    $("#" + divid).html(loader);
    $.get(url, function (data) {
        $("#" + divid).html(data);
    });
}

function IO_ResizeIframe(frameId) {
    var iFrame = document.getElementById(frameId);

    if (($.browser.safari || $.browser.opera) && !$.browser.chrome) {
        // Start timer when loaded.
        window.setTimeout(function () {
            iFrame.style.height = iFrame.contentWindow.document.body.scrollHeight + 'px';
            try { top.resizeIframe() } catch (e) { }
        }, 0);

        var iSource = iFrame.src;
        iFrame.onload = null;
        iFrame.src = '';
        iFrame.src = iSource;
    } else {
        // For other good browsers.
        iFrame.style.height = iFrame.contentWindow.document.body.scrollHeight + 'px';
        try { top.resizeIframe() } catch (e) { }
    }
}

function IO_ScrollRightSide(mintop, noFloatHeight, toppad, bottompad) {
    var rightDiv = $("#content-main-right-float");
    if ($("#content-main").height() <= (rightDiv.height() + toppad + bottompad)) return;
    var scrollTop = $(window).scrollTop();
    var fromTop = 0; var fromBottom = 0;
    if (scrollTop < mintop) fromTop = 0; else fromTop = scrollTop - mintop + toppad;
    var availHeight = $("#content-main").height() - rightDiv.height();
    if (fromTop > (availHeight - noFloatHeight)) {
        fromTop = availHeight - noFloatHeight - toppad - bottompad;
    }
    rightDiv.animate({ top: fromTop + "px" }, { duration: 300, queue: false });
}

function IO_FloatRightSide(toppad, bottompad) {
    if (toppad == undefined) toppad = 10;
    if (bottompad == undefined) bottompad = 10;
    var rightDiv = $("#content-main-right-float");
    rightDiv.css('position', 'relative');
    var actualTop = document.getElementById('content-main-right-float').offsetTop;
    var noFloatHeight = $('#content-main-right-nofloat').height() + Number($("#content-main").css('padding-top').replace('px', '')) + Number($("#content-main").css('padding-bottom').replace('px', ''));
    $(window).scroll(function () { IO_ScrollRightSide(actualTop, noFloatHeight, toppad, bottompad); });
}

function IO_UpdateLiveHelp(active) {
    if (active) $("#content-livehelp").css('display', 'block');
    else $("#content-livehelp").hide();
}

function IO_OpenLiveHelp(url) {
    IO_OpenPopupWindow(url, 'liveChat', 485, 360, 'toolbar=no,directories=no,status=no,scrollbars=no,resizable=no');
}

function IO_OpenMessageOnFly(messageid, title, theme) {
    IO_DialogClose();
    IO_DialogOpen('aj:/message/?messageid=' + messageid + '&fly=1', title, 500, 400, theme, true);
}

var IO_MenuMessagesOrgText = '';
var IO_TopMessagesOrgText = '';
function IO_UpdateNewMessages(count) {
    var mMessages = $("#content-top-menu > ul > li > a#messages");
    var tMessages = $("#content-newmessage");
    if (IO_MenuMessagesOrgText == '') IO_MenuMessagesOrgText = mMessages.html();
    if (IO_TopMessagesOrgText == '') IO_TopMessagesOrgText = tMessages.html();
    mMessages.html(IO_MenuMessagesOrgText + (count > 0 ? ' (' + count + ')' : ''));
    tMessages.html(IO_TopMessagesOrgText.replace('#MessageCount#', count));

    if (count > 0) $("#content-newmessage").css('display', 'block');
    else $("#content-newmessage").hide();
}

function IO_AjaxLoadHistory(url) {
    var hash = url.replace('?', '|');
    hash = hash.replace(/.*\//, '');
    $.history.load(hash);
    $(window).scrollTop(0);
    return false;
}

function IO_InitializeAjaxHistory(divid) {
    var lastReqHash = '';
    var lastReqDate = 0;

    $(document).ready(function () {
        $.history.init(pageLoad);
    });

    function pageLoad(hash) {
        if ((hash == lastReqHash && hash != "") && ((Number(Date.parse(new Date()) / 1000) - lastReqDate) > -2 && (Number(Date.parse(new Date()) / 1000) - lastReqDate) < 2)) return;
        if (hash) {
            lastReqHash = hash;

            var query = '';
            if (hash.indexOf('|') > -1) {
                query = hash.substr(hash.indexOf('|'), (hash.length - hash.indexOf('|')));
                hash = hash.substr(0, hash.indexOf('|'))
            }

            IO_ShowMainLoader();
            $("#" + divid).load('/' + hash + '/' + (query != '' ? query.replace('|', '?') : ''), function () { IO_HideMainLoader() });
        }
    }
}

function IO_ShowMainLoader() {
    $("#main-loader").css('left', Math.round(($(document).width() / 2) - ($("#main-loader").width() / 2)) + 'px')
    $("#main-loader").fadeIn('normal');
}

function IO_HideMainLoader() {
    $("#main-loader").fadeOut('normal');
}

function IO_BoxStatusFromCookie(divId, def) {
    if ($.cookie("io.box.show." + divId) != null) {
        if ($.cookie("io.box.show." + divId) == "1") {
            $("#" + divId).show();
        } else {
            $("#" + divId).hide();
        }
    } else {
        if (def == undefined) def = true;
        if (!def) $("#" + divId).hide();
    }
}

function IO_BoxSlideToggle(divId) {
    if ($("#" + divId).css('display') == "none") {
        $.cookie("io.box.show." + divId, "1", { expires: 7 });
    } else {
        $.cookie("io.box.show." + divId, "0", { expires: 7 });
    }
    $("#" + divId).slideToggle();
}

function IO_IsDefined(variable) {
    return (typeof (window[variable]) == "undefined") ? false : true;
}

function IO_RemoveFromQueryString(key, queryString) {
    if (queryString == null) {
        if (document.location.href.split('?')[1] != null) {
            queryString = document.location.href.split('?')[1];
        } else {
            return;
        }
    }

    if (queryString.substring(0, 1) == '?') queryString = queryString.substring(1, queryString.length);
    if (queryString.indexOf(key) > -1) {
        var splitUrl = queryString.split('&');
        var cleanQuery = new Array();

        for (i = 0; i < splitUrl.length; i++) {
            if (splitUrl[i].substring(0, key.length) != key) {
                cleanQuery.push(splitUrl[i]);
            }
        }

        return (cleanQuery.length > 0) ? cleanQuery = '?' + cleanQuery.join('&') : '';
    } else {
        return queryString;
    }
}

function IO_AddValueToQueryString(key, value, queryString) {
    if (queryString == null) {
        if (document.location.href.split('?')[1] != null) {
            queryString = document.location.href.split('?')[1];
        } else {
            return;
        }
    }

    var isExists = 0; var iFound = 0;
    if (queryString != "" && queryString != null) {
        isExists = queryString.indexOf(key);
        if (isExists > -1) {
            var splitUrl = queryString.split('&');

            if (splitUrl.length > 0) {
                for (i = 0; i < splitUrl.length; i++) {
                    if (splitUrl[i].substring(0, key.length) == key)
                        iFound = i;
                }
                return "?" + queryString.replace(splitUrl[iFound], key + "=" + value);
            } else {
                return "?" + key + "=" + value;
            }
        } else {
            return "?" + queryString + "&" + key + "=" + value;
        }
    } else {
        return "?" + key + "=" + value;
    }
}

function IO_OpenModalWindow(mdUrl, mdWidth, mdHeight, mdResizable, mdScroll) {

    var lPos = (screen.width) ? (screen.width - mdWidth) / 2 : 0;
    var tPos = (screen.height) ? (screen.height - mdHeight) / 2 : 0;
    var xtrStr = "";
    if (!document.all) xtrStr = "; dialogLeft: " + lPos + "; dialogTop: " + tPos; // mozilla

    if (window.showModalDialog) {
        var mdWindow = window.showModalDialog(mdUrl, null, "dialogWidth: " + ((navigator.appVersion.indexOf('MSIE 6.0') > -1) ? (mdWidth + 10) : mdWidth) + "px; dialogHeight: " + ((navigator.appVersion.indexOf('MSIE 6.0') > -1) ? (mdHeight + 50) : mdHeight) + "px; resizable: " + mdResizable + "; scroll: " + mdScroll + xtrStr);
    } else { // firefox 3.0-
        var mdWindow = window.open(url, "modalWindow", "height=" + height + ", width=" + width + ", toolbar=no, directories=no, status=no, scrollbars=" + scroll + ", top=" + topPosition + ", left=" + leftPosition + ", resizable=" + resizable + ", modal=yes");
    }

    return mdWindow;
}

function IO_OpenPopupWindow(url, windowName, width, height, properties) {
    var w = screen.width;
    var h = screen.height - 50;
    var popW = width, popH = height;
    var leftPos = (w - popW) / 2, topPos = (h - popH) / 2;
    var wnd = window.open(url, windowName, 'width=' + popW + ',height=' + popH + ',top=' + topPos + ',left=' + leftPos + ',' + properties);
    return wnd;
}

function IO_DialogOpen(content, title, width, height, theme, overlay, fromTop, fromLeft) {
    theme = (theme) ? theme : 'Default';
    overlay = (overlay) ? overlay : false;
    fromTop = (fromTop) ? fromTop : null;
    fromLeft = (fromLeft) ? fromLeft : null;

    ZWDialog.Alert(content, title, width, height, theme, overlay, fromTop, fromLeft);
}

function IO_DialogClose() {
    ZWDialog.CloseAll();
}

function IO_DialogLastDivID() {
    return ZWDialog.LastAjaxDiv;
}

function IO_OpenFullScreenPopup(url, windowName) {
    var width = screen.availWidth;
    var height = screen.availHeight;
    IO_OpenPopupWindow(url, windowName, width, height, 'resizable=no, scroolbars=no');
}

function IO_SelectRightSubMenu(id) {
    $("#content-main-right-tabs > ul > li > a").removeClass('current');
    $("#content-main-right-tabs > ul > li > #" + id).addClass('current');
}

function IO_EncodeString(str) {
    return str
	.replace(/ç/g, "%C3%A7")
	.replace(/Ç/g, "%C3%87")
	.replace(/ğ/g, "%C4%9F")
	.replace(/Ğ/g, "%C4%9E")
	.replace(/ı/g, "%C4%B1")
	.replace(/İ/g, "%C4%B0")
	.replace(/ö/g, "%C3%B6")
	.replace(/Ö/g, "%C3%96")
	.replace(/ş/g, "%C5%9F")
	.replace(/Ş/g, "%C5%9E")
	.replace(/ü/g, "%C3%BC")
	.replace(/Ü/g, "%C3%9C");
}

function IO_DecodeString(str) {
    return str
	.replace(/%C3%A7/g, "ç")
	.replace(/%C3%87/g, "Ç")
	.replace(/%C4%9F/g, "ğ")
	.replace(/%C4%9E/g, "Ğ")
	.replace(/%C4%B1/g, "ı")
	.replace(/%C4%B0/g, "İ")
	.replace(/%C3%B6/g, "ö")
	.replace(/%C3%96/g, "Ö")
	.replace(/%C5%9F/g, "ş")
	.replace(/%C5%9E/g, "Ş")
	.replace(/%C3%BC/g, "ü")
	.replace(/%C3%9C/g, "Ü");
}

function IO_IsEnterKey(e) {
    var k = e.keyCode || e.which;
    return k == 13;
}

function IO_IsEscapeKey(e) {
    var k = e.keyCode || e.which;
    return k == 27;
}

function IO_GetSelectedText(aWindow) {
    if (!aWindow) aWindow = window;

    if (aWindow.getSelection) {
        return aWindow.getSelection().toString();
    } else if (aWindow.document.getSelection) {
        return aWindow.document.getSelection();
    } else if (aWindow.document.selection) {
        return aWindow.document.selection.createRange().text;
    }
}

function IO_ConvertSeconds(seconds, langSecs, langMins, langHours) {
    if (seconds < 60) { // dakikadan küçükse
        nTime = seconds + ' ' + langSecs;
    } else if (seconds > 59 && seconds < 3600) { //dakikadan byk saatten kkse
        nTime = Math.floor(seconds / 60) + ' ' + langMins
        if ((Math.floor(seconds / 60) * 60) < seconds) { // saniye ksr var
            nTime += ' ' + (seconds - Math.floor(seconds / 60) * 60) + ' ' + langSecs;
        }
    } else { // saatse

        nTime = Math.floor(seconds / 3600) + ' ' + ' ' + langHours;

        if ((Math.floor(seconds / 3600) * 3600) < seconds) { // saniye küsür var belkide dakika
            var precision = seconds - (Math.floor(seconds / 3600) * 3600);

            if (precision > 59) { // demekki dakika var
                nTime += ' ' + Math.floor(precision / 60) + ' ' + langMins;
            }

            if ((Math.floor(precision / 60) * 60) < precision) { // saniye küsürde var masallah
                nTime += ' ' + (precision - (Math.floor(precision / 60) * 60)) + ' ' + langSecs;
            }
        }
    }
    return nTime;
}

// prototype
String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, "");
}
String.prototype.ltrim = function () {
    return this.replace(/^\s+/, "");
}
String.prototype.rtrim = function () {
    return this.replace(/\s+$/, "");
}

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (elt /*, from*/) {
        var len = this.length;

        var from = Number(arguments[1]) || 0;
        from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
        if (from < 0)
            from += len;

        for (; from < len; from++) {
            if (from in this &&
          this[from] === elt)
                return from;
        }
        return -1;
    };
}
// -- prototype