﻿$(function()
{
    $("a[rel*=roaming]").click(function() { loadRoamingTariffs(this); return false; });

    $(".nl2 ul > li:last-child").each(function() {
        this.className = (this.className || "") + " last-child";
    });
    

    // Set default classes for content table tags
    setTablesStyles();
    // Set type for files
    processFileList();


    // simulate same stuff that exists in region selector
    region_name = '';
    var current_host = document.domain.replace('www.', '');//'spb.tele2.ru';
    var current_host_parts = current_host.split('.');
    current_region = current_host_parts[0];

    $(".regions-list a").each(function()
    {
        var host = get_host_name(this.href);
        host = host.replace('www.', '');
        var hostParts = host.split('.');
        var region = hostParts[0];

        
        if (region == current_region)
        {
            region_name = $(this).text();
        }
    })


    if ($("#top .nav1").find("li.cur").index() == 1) //b2b same title for all
    {
        document.title = 'Tele2 ' + region_name + ' корпоративным клиентам';        
    }
    else //b2c title same for all
    {
        document.title = 'Tele2 ' + region_name;
    }
    
    doArticlePaging();


    $(".nav1 li").each(function()
    {
        var b2b_link = $(this).find("a").attr('href').indexOf("business.html");
        if (b2b_link > -1)
        {
            if ($(this).attr('class') != 'cur')
            {
                $(this).addClass('b2b');
                Cufon.replace($(this)); 
            }
        }
    });
});


function loadRoamingTariffs(linkObj)
{
    $.getJSON('http://new.tools.tele2.ru/' + $(linkObj).attr("href") + '&jsonp_callback=showRoamingTariffs&jsoncallback=?', function (){});
}

function showRoamingTariffs(data)
{
    
    // Fancybox way: works fine, but popup css sould be adjusted
    /*$.fancybox(
        data,
        {
            'autoDimensions' : false,
            'width' : 580,
            'height' : 'auto',
            'showCloseButton' : false,
            'scrolling': 'no',
            'overlayOpacity': 0.2
        }
    );
    $(".popup a.close").click(function() {
        $.fancybox.close();
    });*/
    $("body").append(data);
    $(".popup a.close").click(function() {
        $(".popup-overlay").remove();
        $(".popup").remove();
    });
}

function setTablesStyles()
{
    $(".content table[class!=contactform]").addClass("goodnums");

    $(".colcenterb2b .content table").removeClass("goodnums"); //remove that annoying zebra from business tables
    $(".transparent-content .content table").removeClass("goodnums");
    $(".colwideb2b .content table").removeClass("goodnums");

    $(".goodnums").each(function(){ $(this).find("tr:odd").addClass("even"); });
    $(".goodnums tr").each(function(){ $(this).find("td:last").addClass("num"); });
    $(".goodnums").each(function(){
        $(this).find("tr:first").css('font-size', '14px');
        //$(this).find("tr:first td").each( function() { $(this).wrapInner('<strong>'); });
    });

    
}

function processFileList()
{
    $("ul.files a").each(function(){
        var file = $(this).attr('href');
        var parts = file.split('.');
        var icon = '/img/download-files/__.gif';
        if (parts.length > 0) {
            var extension = parts[parts.length-1];
            $(this).text($(this).text().replace('(', '(' + extension.toUpperCase() + ', '));
            
            switch (extension.toLowerCase()) {
                case 'pdf':
                    icon = '/img/download-files/pdf.gif';
                break;

                case 'rtf':
                case 'doc':
                case 'docx':
                    icon = '/img/download-files/doc.gif';
                break;

                case 'xls':
                case 'xlsx':
                    icon = '/img/download-files/xls.gif';
                break;

                case 'jpg':
                case 'jpeg':
                case 'gif':
                case 'png':
                case 'bmp':
                    icon = '/img/download-files/jpg.gif';
                break;

                case 'rar':
                case '7z':
                case 'tar':
                case 'gz':
                case 'zip':
                    icon = '/img/download-files/rar.gif';
                break;

                case 'ppt':
                    icon = '/img/download-files/ppt.gif';
                break;
            }
            $(this).parent().css('background', 'url("' + icon + '") no-repeat scroll left top transparent');
        }
    });
}

function get_host_name(str) // function getHostname exists in all pages
{ 
    var re = new RegExp('^(?:f|ht)tp(?:s)?\://([^/]+)', 'im'); 
    return str.match(re)[1].toString(); 
}


function doArticlePaging()
{
    var articlesPerPage = 10;
    
    if ($(".news-list li").size() > articlesPerPage)
    {
        var articleCount = 1;
        var pageCount = 1;
        $(".news-list li").each(function (i)
        {
            if (articleCount == 1)
            {
                $(".news-list").append("<div class=\"pages\" id=\"page-" + pageCount +"\"></div>");
            }
            
            $("#page-" + pageCount).append($(this)).append($("hr:first"));
            if (articleCount == articlesPerPage)
            {
                articleCount = 1;
                pageCount++;
            }
            else
            {
                articleCount++;
            }
        });
        
        $(".pages:not(:first)").hide();
        $(".pages:first").show();
        $(".paging").before("<ul id=\"pagination\"></ul>");
        
        pageLinkCount = 1;
        
        $(".pages").each(function (i) {
            $("#pagination").append("<li><a href=\"#page-" + pageLinkCount + "\" rel=\"page-" + pageLinkCount + "\">" + pageLinkCount + "</a></li>");
            pageLinkCount++;
        }
        );
        $("#pagination li:first").addClass("active-page");
        $("#pagination").prepend("<li class=\"previous-page\"><a href=\"#\">&nbsp;</a></li>");
        $("#pagination").append("<li class=\"next-page\"><a href=\"#\">&nbsp;</a></li>");
        $("#pagination li a:not(:first):not(:last)").bind("click", function(e) {
            $("#pagination li.active-page").removeClass("active-page");
            $(this).parent().addClass("active-page");
            $(".pages").hide();
            curHash = $("#pagination li.active-page a").attr("href");
            var regex = /#.+/g;
            if(regex.test(curHash)) {
                curHash = curHash.match(regex).toString();
            }
            $(curHash).show();
            e.preventDefault(e);
        }
        );
        function getPageNumber(testString) {
            var regex = /\d+/;
            if(regex.test(testString))
            {
                var match = testString.match(regex);
                match = parseFloat(match); 
                return match;
            }
        }
        $("#pagination .previous").bind("click", function(e) {
            curHash = $("#pagination li.active-page a").attr("href");
            var regex = /#.+/g;
            if(regex.test(curHash)) {
                curHash = curHash.match(regex).toString();
            }
            if (getPageNumber(curHash) != '1') {
                $("#pagination li.active-page").prev().addClass("active-page");
                $("#pagination li.active-page:last").removeClass("active-page");
                $(".pages:visible").hide();
                nextPage = getPageNumber(curHash)-1;
                $('#page-'+nextPage).show();
            }
            e.preventDefault(e);
        }
        );
        $("#pagination .next").bind("click", function(e) {
            curHash = $("#pagination li.active-page a").attr("href");
            var regex = /#.+/g;
            if(regex.test(curHash)) {
                curHash = curHash.match(regex).toString();
            }
            totalPages = $(".pages").length;
            if (getPageNumber(curHash) != totalPages) {
                $("#pagination li.active-page").next().addClass("active-page");
                $("#pagination li.active-page:first").removeClass("active-page");
                $(".pages:visible").hide();
                nextPage = getPageNumber(curHash)+1;
                $('#page-'+nextPage).show();
            }
            e.preventDefault(e);
        }
        );
    }
}


function Set_Cookie( name, value, expires, path, domain, secure )
{
  // set time, it's in milliseconds
  var today = new Date();
  today.setTime( today.getTime() );
  
  /*
  if the expires variable is set, make the correct
  expires time, the current script below will set
  it for x number of days, to make it for hours,
  delete * 24, for minutes, delete * 60 * 24
  */
  if ( expires )
  {
    expires = expires * 1000 * 60 * 60 * 24;
  }
  
 
  var expires_date = new Date( today.getTime() + (expires) );
  
  document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}

function Get_Cookie( check_name )
{
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f
    for ( i = 0; i < a_all_cookies.length; i++ )
    {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split( '=' );
        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
        // if the extracted name matches passed check_name
        if ( cookie_name == check_name )
        {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if ( a_temp_cookie.length > 1 )
            {
                cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if ( !b_cookie_found )
    {
        return null;
    }
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain )
{
  if ( Get_Cookie( name ) ) document.cookie = name + "=" +
  ( ( path ) ? ";path=" + path : "") +
  ( ( domain ) ? ";domain=" + domain : "" ) +
  ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
