﻿function openModalWindow(title, url, height, width) {
    $.fancybox({
        'width': width,
        'height': height,
        'autoScale': true,
        'transitionIn': 'none',
        'transitionOut': 'none',
        'type': 'iframe',
        'href': url
    });
}
function showPopupMessage(id) {
    $("#" + id).ready(function () {
        document.getElementById(id).style.display = "";
    });
}

function hidePopupMessage(id) {
    if (document.getElementById(id) != null)
        $("#" + id).ready(function () {
            document.getElementById(id).style.display = "none";
        });
}
function TipI(docPage, newsTitle, thumbUrl) { Tip('<a href="' + docPage + '"><img src="' + thumbUrl.replace("thumbnail_", "headline_") + '"/></a><span class=line1><a href="' + docPage + '">' + newsTitle + '</a></span><span class=line2><a href="' + docPage + '" class="downloadLinkButton"></a></span>'); }

function PrintShow(url) { window.open(url, "Print", "status = 1, height=600, width=800, resizable=0,top=40,left=75,scrollbars=1"); }

function PrintNews(id) { $.fn.colorbox({ width: "50%", height: "50%", href: '<%=Request.ApplicationPath=="/" ? "":Request.ApplicationPath%>/news/PrintNews.aspx?NewsId=' + id + '', iframe: true, open: true, overlayClose: false }); }

function showSignUp(id) { $.fn.colorbox({ width: "850px", height: "500px", href: '<%=Request.ApplicationPath=="/" ? "":Request.ApplicationPath%>/SignUpwindow.aspx?type=' + id, iframe: true, open: true, overlayClose: false }); }

function showSignUpReturn(ReturnUrl) { $.fn.colorbox({ width: "750px", height: "300px", href: '<%=Haberol.Manager.ManagerRegistry.SingleInstance.ConfigManager.GetConfigParameterValue("ajansbizDomain") %>/security/loginwindow.aspx?returnUrl=' + ReturnUrl, iframe: true, open: true, overlayClose: false }); }

function showNews(url) {
    $.fn.colorbox({ width: "910px", height: "90%", href: url, iframe: true, open: true, overlayClose: false });
}

//jquery.cookie plugin.
jQuery.cookie = function (key, value, options) {
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);
        if (value === null || value === undefined) {
            options.expires = -1;
        }
        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }
        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '',
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

$(document).ready(function () {

    LoadSearchParameters();
    loadNewsContent();

    $("#txt_searchText").focus(function () {
        $("#txt_searchText").animate({ width: "166px" });
    });
    $("#txt_searchText").blur(function () {
        $("#txt_searchText").animate({ width: "80px" });
    })
    $("#txt_searchText").keypress(function (e) {
        code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) { $(".headerSearchButton").click(); e.preventDefault(); }
    });
    acCompanyHeader();
    if ($(".sCompany").val() == "")
        $(".sCompany").val($(".sCompany").attr("title"));
    $(".sCompany").click(function () {
        if ($(".sCompany").val() == "" || $(".sCompany").val() == $(".sCompany").attr("title"))
            $(".sCompany").val("");
    });
    $(".sCompany").blur(function () {
        if ($(".sCompany").val() == "")
            $(".sCompany").val($(".sCompany").attr("title"));
    });
    $(".sCompany").keypress(function (e) {
        code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) { sCompany_click(); e.preventDefault(); }
    });
    $(".searchcontainerNews.vn").keypress(function (e) {
        code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) { $(".newsSearchButton.vn").click(); e.preventDefault(); }
    });
    $("#typeSelector:parent").hover(function () {
        $(".menuSelector-content").show().css("z-index", 9999);
        $("#typeSelector").addClass("active");
    },
    function () {
        $(".menuSelector-content").hide().css("z-index", 0);
        $("#typeSelector").removeClass("active");
    });
    $(".menuSelector-content ul li").click(function () {
        $("a#qAF span").html($("label", this).html());
    });
    if (($.browser.msie && $.browser.version < 8.0)) {
        $(".signUpFree").hover(function () {
            $(".login-content").css("left", "-50px");
        }, function () { $(".login-content").css("left", "-999em"); });
        $("div.loginContainer a.signUpFree").attr("href", "");
    }
    !function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (!d.getElementById(id)) { js = d.createElement(s); js.id = id; js.src = "//platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs); } } (document, "script", "twitter-wjs");
    if ($.isFunction($.fn.selectbox))
        $("div.searchlineNews select").selectbox();
    if ($.isFunction($.fn.scrollable)) {
        $(".shBox.Nav").scrollable({ size: 1, prev: '.shTitle.Control .prev', next: '.shTitle.Control .next', clickable: false });
        $(".m.autoScrollable").scrollable({ size: 1, prev: '', next: '', circular: true, clickable: false }).navigator({ navi: '.mnavi' }).autoscroll({ autoplay: true, interval: 10000, autostop: true });
        $(".attachedNewsFiles .scrollable.itemsC").scrollable({ size: 1, circular: false, clickable: false }).navigator();
    }
    if ($.isFunction($.fn.peepshow))
        $("#galery").peepshow({ crop: [248, 166] });
    $(".News").hover(function () {
        $(".LogoContainer", this).css("height", $(".Logo img", this).height() + 12);
        $(".Logo", this).css("position", "absolute");
        $(".Follow", this).css("display", "block");
        if ($(".Follow iframe", this).length == 0) {
            $(".Follow .stIframe", this).after("<iframe width=\"100\" height=\"20\" scrolling=\"no\" frameBorder=\"0\" src=\"" + $(".Follow .stIframe", this).attr('href') + "\"></iframe>");
            $(".Follow .stIframe", this).remove();
        }
    }, function () {
        $(".LogoContainer", this).css("height", "auto");
        $(".Logo", this).css("position", "relative");
        $(".Follow", this).css("display", "none");
    });

    if ($(".searchlineNews .txtKeyword").length > 0)
        $(".searchlineNews .txtKeyword").catcomplete({
            delay: 0,
            width: 284,
            source: jsShDomain + "/cache/ac.aspx",
            select: function (event, ui) {
                window.location = ui.item.url;
            }

        });
    if ($(".searchlineNews .actxtCompanyAccountName").length > 0)
        acCompany();
    if ($(".stIframeReplace").length == 1) {
        $(".stIframeReplace").after("<iframe width=\"173\" height=\"49\" scrolling=\"no\" frameBorder=\"0\" src=\"" + $(".stIframeReplace").attr("href") + "\"></iframe>");
        $(".stIframeReplace").remove();
    }
    showAnnouncement();
    //Fix for LinkedIn button for Chrome
    if (navigator.userAgent.indexOf('Chrome') != -1)
        $(".m.autoScrollable .items .CountBox ul li:last-child").addClass("chromeFix");
    //This should remain at the end of document ready at all times.
    LogList();
    LogDisplay();
    $("#newsContent a").click(function () { });

    $(".st.subl li").hover(function () {
        if ($(".fContainer iframe", this).length == 0) {
            $(".fContainer .stIframe", this).after("<iframe width=\"100\" height=\"20\" scrolling=\"no\" frameBorder=\"0\" src=\"" + $(".fContainer .stIframe", this).attr('href') + "\"></iframe>");
            $(".fContainer .stIframe", this).remove();
        }
    });

});
function resizeSigninIframe(signedIn) {
    if (signedIn == '0') {
        $("iframe.ifrSignin").attr("width", '70');
        $(".loginContainer").show();
        $("#hSoTa").show();
    }
    else {
        $("iframe.ifrSignin").attr("width", '500');
        $(".loginContainer").hide();
        $("#hSoTa").hide();
    }
}
function BringScriptDocument(scribdDocId, scribdAccessKey) {
    var scribd_doc = scribd.Document.getDoc(scribdDocId, scribdAccessKey);
    var oniPaperReady = function (e) {
    }
    scribd_doc.addParam('jsapi_version', 1);
    scribd_doc.addParam('height', 400);
    scribd_doc.addParam('width', 400);
    scribd_doc.addParam('mode', 'scroll');
    scribd_doc.addParam('public', true);
    scribd_doc.addEventListener('iPaperReady', oniPaperReady);
    scribd_doc.write('scribdDocumentContainer');
}

function search_click(keyword, domain) {
    window.location = domain + '/mainpage/newslist.aspx?keyword=' + (keyword == 'Anahtar Kelime Ara' ? '' : keyword);
}
function showCompanyLogoDiv()
{ Tip($('#companyLogoDownload').html()); }

function copyAttachedFiles(panelId) {
    if ($("#dropImgContent").html() == "") {
        $("#" + panelId + " .file-item").each(function () {
            $("#dropImgContent").html($("#dropImgContent").html() + "<div class=\"file-item h80\">" + $(this).html() + "</div>");
        });
        $("#dropImgContent img").removeAttr("onmouseover");
    }
}
function acCompany() {
    $(".searchlineNews .actxtCompanyAccountName").autocomplete({ source: jsShDomain + "/cache/ac.aspx?company=1", width: 140, top: 0, left: 16, minChars: 1, max: 100, content: 'ac_body_news', mustMatch: false, selectFirst: false, select: function (event, ui) {
        $(".actxtCompanyAccountNameHid").val(ui.item.urlName);
    }
    });
}
function acCompanyHeader() {
    $("#txt_searchText").catcomplete({
        delay: 0,
        width: 200,
        minChars: 2,
        left: 16,
        source: jsShDomain + "/cache/ac.aspx",
        select: function (event, ui) {
            window.location = ui.item.url;
        }
    });
    //.autocomplete({source:curDomain + "/mainpage/newslist.aspx", width: 200, top: 0, left: 16, minChars: 2, max: 100, mustMatch: false, selectFirst: false });
}

function CreateSearchURL(searchMethod) {

    var keyword = searchParameters.Keyword.Name;
    var subject = searchParameters.Subject.URLName;
    var sector = searchParameters.Sector.URLName;
    var company = searchParameters.Company.URLName;
    var tag = searchParameters.Tag.URLName;
    var city = searchParameters.City.URLName;

    sm = "haber-arama";
    searchM = 0;
    switch (searchMethod) {
        case 0:
            if ($('.lbNews').hasClass('bold')) {
                sm = "haber-arama";
                searchM = 0;
            }
            else if ($('.lbImage').hasClass('bold')) {
                sm = "gorsel-arama";
                searchM = 1;
            }
            else if ($('.lbDocument').hasClass('bold')) {
                sm = "dokuman-arama";
                searchM = 3;
            }
            else {
                sm = "haber-arama";
                searchM = 0;
            }

            break;
        case 1:
            sm = "haber-arama";
            searchM = 0;
            break;
        case 2:
            sm = "gorsel-arama";
            searchM = 1;
            break;
        case 3:
            sm = "dokuman-arama";
            searchM = 3;
            break;
        case 4:
            sm = "video-arama";
            searchM = 2;
            break;
    }

    var searchURL = jsShDomain + '/mainpage/newslist.aspx';

    var params = ['0', '0', '0', '0', '0', '0', '0'];
    if (company != '')
        params[0] = 'company=' + encodeURIComponent(company);
    if (sector != '')
        params[1] = 'sector=' + sector;
    if (subject != '')
        params[2] = 'subject=' + subject;
    if (city != '')
        params[3] = 'city=' + city;
    if (keyword != '')
        params[4] = 'keyword=' + keyword.replace('&', '%26'); ;
    if (tag != '')
        params[5] = 'tag=' + tag;
    if (searchM != 0)
        params[6] = 'SearchMethod=' + searchM;

    for (i = 0; i < params.length; i++) {
        if (params[i] != '0') {
            if (searchURL.indexOf("?") == -1)
                searchURL += '?' + params[i];
            else
                searchURL += '&' + params[i];
        }
    }
    window.top.location = searchURL;
}

function ShareThis(site, title, url, imageUrl) {
    url = encodeURI(url.replace("&IsGuests=true", ""));
    imageUrl = encodeURI(imageUrl);
    title = encodeURI(title);
    var SheraArray = [];
    SheraArray["Facebook"] = "http://www.facebook.com/sharer.php?u=" + url + "&t=" + title;
    SheraArray["Twitter"] = "http://twitter.com/home?status=" + title + "%20" + url;
    SheraArray["Linkedin"] = "http://www.linkedin.com/shareArticle?mini=true&url=" + url + "&title=" + title + "&source=Şirket Haberleri";
    if (site != "") {
        window.open(SheraArray[site], site, "status = 1, height=600, width=800, resizable=0,top=40,left=75,scrollbars=1");
    }
}

var detSearchopen = false;
function toggleDetailSearchLine() {
    if (!detSearchopen) {

        $(".sLine2 select").selectBox({ autoWidth: true });
        detSearchopen = true;
    }
    /*if ($(".sLine2").is(':visible'))
    $(".sLine2").removeClass("clicked round4");
    else { $(".sLine2").addClass("clicked round4"); }*/
    $(".sLine2").toggle();

    if ($(".newsDetailButton").hasClass("active"))
        $(".newsDetailButton").attr("class", "newsDetailButton");
    else
        $(".newsDetailButton").attr("class", "newsDetailButton active");

}

(function (d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) { return; }
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/tr_TR/all.js#xfbml=1";
    fjs.parentNode.insertBefore(js, fjs);
} (document, 'script', 'facebook-jssdk'));

/*Category based autocomplete*/
$.widget("custom.catcomplete", $.ui.autocomplete, {
    _renderMenu: function (ul, items) {
        var self = this,
				currentCategory = "";
        $.each(items, function (index, item) {
            if (item.category != currentCategory) {
                ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
                currentCategory = item.category;
            }
            self._renderItem(ul, item);
        });
    }
});
function sosyalTakipciTip(title, rss) {
    Tip('<div class=\"followBoxInnerTip gradDADA\"><h3 class=\"title\">' + title + ' haberleri</h3><iframe scrolling=\"no\" frameBorder=\"0\" width=\"173\" height=\"49\" src=\"' + jsStDomain + '/follow.aspx?url=' + rss + '&cKey=1&type=large\"></iframe></div>');
}
function showAnnouncement() {
    if ($.cookie('noAnnouncement') == '1')
    { }
    else {
        $("body").prepend($("#paCont").html());
        $("#paCont").remove();
        $(".pnlAnnounce").show();
        $("body").css("margin-top", "30px");
    }
}
function hideAnnouncement() {
    $('.pnlAnnounce').fadeOut('slow'); $.cookie('noAnnouncement', '1', { expires: 2, path: '/' }); $("body").css("margin-top", "0px");
}

function LogList() {
    var logNewsIds = "";
    $(".m.autoScrollable .item .Text").each(function () {
        if ($(this).parent().attr("class").indexOf("cloned") == -1)
            logNewsIds += logHelperGetIdFromPattern("shni_", $(this).attr("class"));
    });
    $(".m.right .desc").each(function () {
        logNewsIds += logHelperGetIdFromPattern("shni_", $(this).attr("class"));
    })
    $(".News.cf").each(function () {
        logNewsIds += logHelperGetIdFromPattern("shni_", $(this).attr("class"));
    });
    $(".desc a").each(function () {
        logNewsIds += logHelperGetIdFromPattern("shni_", $(this).attr("class"));
    });

    if (logNewsIds != "")
        $.post(jsShDomain + "/analytics/sh.aspx", { redir: document.referrer, newsId: logNewsIds, userId: logHelperGetUser(), accessType: "15" });
}
function LogDisplay() {
    var className = $("h1").attr('class');
    if (className) {
        if (className.indexOf('shdni_') != -1)
            $.post(jsShDomain + "/analytics/sh.aspx", { redir: document.referrer, newsId: logHelperGetIdFromPattern("shdni_", className), userId: logHelperGetUser(), accessType: "5" });
        else if (className.indexOf('shddi_') != -1) {
            var accessTypeStr = '';
            switch ($("#shDocType").val()) {
                case "image":
                    accessTypeStr = "6";
                    break;
                case "document":
                    accessTypeStr = "10";
                    break;
                case "video":
                    accessTypeStr = "8";
                    break;
            }
            $.post(jsShDomain + "/analytics/sh.aspx", { redir: document.referrer, docId: logHelperGetIdFromPattern("shddi_", className), userId: logHelperGetUser(), accessType: accessTypeStr });
        }
    }
}
function LogClick(clickUrl, newsId, organisationID) {
    $.post(jsShDomain + "/analytics/sh.aspx", { redir: document.referrer, newsId: newsId, orgId: organisationID, userId: logHelperGetUser(), cUrl: clickUrl, accessType: "16" });
}
function LogDownload() {
    var className = $("h1").attr('class');
    var downloaddocID = logHelperGetIdFromPattern('shddi_', className);
    var accessTypeStr = '';
    switch ($("#shDocType").val()) {
        case "image":
            accessTypeStr = "7";
            break;
        case "document":
            accessTypeStr = "11";
            break;
        case "video":
            accessTypeStr = "9";
            break;
    }
    $.post(jsShDomain + "/analytics/sh.aspx", { redir: document.referrer, docId: downloaddocID, userId: logHelperGetUser(), accessType: accessTypeStr });
}
function logHelperGetIdFromPattern(pattern, className) {
    var ret = "";
    if (className) {
        var idStart = className.indexOf(pattern);
        if (idStart != -1) {
            try {
                ret = className.substring(idStart + pattern.length, className.length) + ",";
            }
            catch (err) { return ""; }
        }
    }
    return ret;
}

function logHelperGetUser() {
    var cookieVal = $.cookie("ajansbiz");
    var userName = "";
    if (cookieVal && cookieVal != "") {
        userName = cookieVal.substring(9, cookieVal.indexOf('&'));
    }
    return userName;
}
function securityCheckUser() {
    var cookieVal = $.cookie("ajansbiz");
    var userName = "";
    var secret = "";
    var retVal = '';
    if (cookieVal && cookieVal != "") {
        userName = cookieVal.substring(9, cookieVal.indexOf('&'));
        secret = cookieVal.substring(cookieVal.indexOf("s_key=") + 6, cookieVal.length);
        $.ajax({ url: jsShDomain + "/security/check.aspx",
            type: "GET",
            data: "un=" + userName + "&s_key=" + secret,
            async: false,
            success: function (data) { retVal = data; }
        });
    }
    return retVal;
}

function DownloadDocument(docUrl) {
    var secRes = securityCheckUser();
    if (secRes == 't') {
        docUrl = jsHbrlDwnldDomain + docUrl;
        window.open(docUrl, 'Download');
        LogDownload();
    }
    else {
        window.location = jsShDomain + "/security/LoginPage.aspx?returnUrl=" + window.location + "&download=" + $("#shDocType").val();
    }
}

function DownloadLogo(logoUrl) {
    var secRes = securityCheckUser();
    if (secRes == 't') {
        logoUrl = jsAjansDwnldDomain + logoUrl;
        window.open(logoUrl, 'Download');
        LogDownload();
    }
    else {
        window.location = jsShDomain + "/security/LoginPage.aspx?returnUrl=" + window.location + "&download=image";
    }
}

function userAction(actionType, newsId, orgId) {
    var secRes = securityCheckUser();
    if (secRes == 't') {
        switch (actionType) {
            case "archive":
                $.post(jsShDomain + "/user/action.aspx", { type: actionType, userId: logHelperGetUser(), newsId: newsId, orgId: orgId });
                $(".addToArchive").text("Haber arşivinize eklendi");
                $(".addToArchive").attr("onclick", "");
                break;
            case "profile":
                $.post(jsShDomain + "/user/action.aspx", { type: actionType, userId: logHelperGetUser(), newsId: newsId, orgId: orgId });
                $(".addToProfile.action").text("Takiptesin");
                $(".addToProfile.action").attr("onclick", "");
                break;
        }
    }
    else {
        window.location = jsShDomain + "/security/LoginPage.aspx?returnUrl=" + window.location;
    }
}
function loadNewsContent() {
    if ($("#newsContent font.contentPart2").length > 0) {
        var secRes = securityCheckUser();
        if (secRes == 't') {
            $("#newsContent font.contentPart2").before($("#newsContent font.contentPart2").html());
            $("#newsContent font.contentPart2").remove();
        } else {
            $("#newsContent font.contentPart2").remove();
            $("#newsContent p:last").html($("#newsContent p:last").html() + "...<div class='marginTop15 marginBottom10'><input class='gbutton black' type='button' value='Haberin Devamı' onclick=\"window.top.location='" + jsShDomain + "/security/LoginPage.aspx?returnUrl=" + document.URL + "';\"/></div>");
        }
    }
}
function RemoveSearchParameter(type) {
    searchParameters[type].Name = '';
    searchParameters[type].URLName = '';
    $("li." + type).hide();
    CreateSearchURL(0);
}
function LoadSearchParameters() {
    if (typeof searchParameters !== "undefined") {
        var spCount = 0;
        for (var x in searchParameters) {
            if (searchParameters[x].Name != '') {
                spCount++;
                $('.ulParameters').append('<li class=\'' + x + '\'>' + searchParameters[x].Name + '<input type=\'button\' class=\'btnDel\' onclick=\'RemoveSearchParameter("' + x + '");\' /></li>');
            }

            if (spCount > 0)
                $('.SearchParameters').show();
            else
                $('.SearchParameters').hide();
        }
    }
}
function Search() {
    if ($('.sLine1 .txtKeyword').val() != $('.sLine1 .txtKeyword').attr('title')) {
        searchParameters.Keyword.Name = encodeURIComponent($('.sLine1 .txtKeyword').val());
        searchParameters.Keyword.URLName = encodeURIComponent($('.sLine1 .txtKeyword').val());
    }

    if ($('.sCompanyContainer .actxtCompanyAccountName').val() != $('.sCompanyContainer .actxtCompanyAccountName').attr('title')) {
        searchParameters.Company.Name = encodeURIComponent($('.sCompanyContainer .actxtCompanyAccountName').val());
        searchParameters.Company.URLName = encodeURIComponent($('.sCompanyContainer .actxtCompanyAccountNameHid').val());
    }
    CreateSearchURL(0);
}
