String.prototype.wordWrap = function(m, b, c){
    var i, j, l, s, r;
    if(m < 1)
        return this;
    for(i = -1, l = (r = this.split("\n")).length; ++i < l; r[i] += s)
        for(s = r[i], r[i] = ""; s.length > m; r[i] += s.slice(0, j) + ((s = s.slice(j)).length ? b : ""))
            j = c == 2 || (j = s.slice(0, m + 1).match(/\S*(\s)?$/))[1] ? m : j.input.length - j[0].length
            || c == 1 && m || j.input.length + (j = s.slice(m).match(/^\S*/)).input.length;
    return r.join("\n");
};
Array.prototype.sum = function() {
  return (! this.length) ? 0 : this.slice(1).sum() +
      ((typeof this[0] == 'number') ? this[0] : 0);
};

function validEmail(el){
  return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test($(el).val());
}
function linksExternal(){
    $("a[rel='external']").each(function(i){ 
        this.target = "_blank"; 
    });
}
function time () {
    // Return current UNIX timestamp  
    // 
    // version: 1004.2314
    // discuss at: http://phpjs.org/functions/time
    // +   original by: GeekFG (http://geekfg.blogspot.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: metjay
    // +   improved by: HKM
    // *     example 1: timeStamp = time();
    // *     results 1: timeStamp > 1000000000 && timeStamp < 2000000000
    
    return Math.floor(new Date().getTime()/1000);
}
function requiredDecorator(){
    $('label.required').each(function(i){
        var tmp = $(this).text();
        $(this).html(tmp + '<span class="required">*</span>');
    });
}
function sanatizeString(str){
  var toReplace = {
      '|': '-',
      '!': '-',
      '"': '-',
      '\'': '-',
      '£': '-',
      '%': '-',
      '&': '-',
      '/': '-',
      '(': '-',
      ')': '-',
      '[': '-',
      ']': '-',
      '{': '-',
      '}': '-',
      '=': '-',
      '?': '-',
      '^': '-',
      '°': '-',
      '*': '-',
      '§': '-',
      '@': '-',
      '#': '-',
      '_': '-',
      '+': '-',
      ';': '-',
      '.': '-',
      ',': '-',
      ':': '-',
      '<': '-',
      '>': '-',
      ' ': '-',
      'à': 'a',
      'è': 'e',
      'é': 'e',
      'ì': 'i',
      'ò': 'o',
      'ù': 'u',
      'ç': 'c'
  };
  var string = str.replace(/./g, function (match) {
      return toReplace[match] || match;
  });

  return string.toLowerCase().substring(0, 255);
}
function in_array (needle, haystack, argStrict) {
    // Checks if the given value exists in the array  
    // 
    // version: 911.718
    // discuss at: http://phpjs.org/functions/in_array
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true
    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
    var key = '', strict = !!argStrict;
 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }
 
    return false;
}
function strip_tags (str, allowed_tags) {
    // Strips HTML and PHP tags from a string  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/strip_tags
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Luke Godfrey
    // +      input by: Pul
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +      input by: Alex
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Marc Palau
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Eric Nagel
    // +      input by: Bobby Drake
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Tomasz Wesolowski
    // *     example 1: strip_tags('<p>Kevin</p> <b>van</b> <i>Zonneveld</i>', '<i><b>');
    // *     returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'
    // *     example 2: strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>');
    // *     returns 2: '<p>Kevin van Zonneveld</p>'
    // *     example 3: strip_tags("<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>", "<a>");
    // *     returns 3: '<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>'
    // *     example 4: strip_tags('1 < 5 5 > 1');
    // *     returns 4: '1 < 5 5 > 1'
    var key = '', allowed = false;
    var matches = [];
    var allowed_array = [];
    var allowed_tag = '';
    var i = 0;
    var k = '';
    var html = '';
 
    var replacer = function (search, replace, str) {
        return str.split(search).join(replace);
    };
 
    // Build allowes tags associative array
    if (allowed_tags) {
        allowed_array = allowed_tags.match(/([a-zA-Z0-9]+)/gi);
    }
 
    str += '';
 
    // Match tags
    matches = str.match(/(<\/?[\S][^>]*>)/gi);
 
    // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;
        }
 
        // Save HTML tag
        html = matches[key].toString();
 
        // Is tag not in allowed list? Remove from str!
        allowed = false;
 
        // Go through all allowed tags
        for (k in allowed_array) {
            // Init
            allowed_tag = allowed_array[k];
            i = -1;
 
            if (i !== 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i !== 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i !== 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}
 
            // Determine
            if (i === 0) {
                allowed = true;
                break;
            }
        }
 
        if (!allowed) {
            str = replacer(html, "", str); // Custom replace. No regexing
        }
    }
  return str;
}
function urlencode (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer
    // +      input by: Ratheous
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Joris
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // %          note 1: This reflects PHP 5.3/6.0+ behavior
    // %        note 2: Please be aware that this function expects to encode into UTF-8 encoded strings, as found on
    // %        note 2: pages served as UTF-8
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'

    str = (str+'').toString();

    // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
    // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
                                                                    replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}

function tvnDropDownMenu(){
    var firstItem = $('#searchWithinTheChannel > option:eq(0)').text();
    //$("#within").val('yyyyy');
    function stylishSelect(){
        $('#searchWithinTheChannel').hide();
        var menu = '<dl id="tvnSearchMenu" class="dropdown">';
        menu += '<dt><a href="#"><span>'+firstItem+'</span></a></dt>';
        menu +=  '<dd><ul>';
        $('#searchWithinTheChannel > option').each(function(index) {
           if(index !== 0){
                menu += '<li><a href="#">'+$(this).text()+'<span class="value">'+$(this).val()+'</span></a></li>';
           }
        });
          menu += '</ul></dd></dl><span id="result" style="display:none"></span>';
          $('#searchSelectContainer').html(menu);
    }

    stylishSelect();
    var ulBckColor = $("#tvnSearchMenu ul").css("background-image");
    
    $("#tvnSearchMenu ul li:odd").css("background-image", "url(/static/images/default/bckBrightLinkSelectMenu.png)");
    $(".dropdown dt a").click(function() {
       $("#result").html('');
       $(".dropdown dd ul").toggle();
            return false;
    });

    $(".dropdown dd ul li a").click(function() {
        var text = $(this).html();
        $(".dropdown dt a span").html(text);
        if($('#stake').length === 0){
            $('<li id="stake"><a href="#">'+firstItem+'<span class="value"></span></a></li>').insertBefore('.dropdown dd ul li:eq(0)');
            $('#stake').click(function(){
                var text = $(this).text();
                $(".dropdown dt a span").html(text);
                $(".dropdown dd ul").hide();
                $('#stake').remove();
                return false;
            });
        }
        $(".dropdown dd ul").hide();
        $("#result").html(getSelectedValue("tvnSearchMenu"));
        $("#tvnSearchMenu ul li").css("background-image",ulBckColor);
        $("#tvnSearchMenu ul li:odd").css("background-image", "url(/static/images/default/bckBrightLinkSelectMenu.png)");
        return false;
    });

    function getSelectedValue(id) {
       return $("#" + id).find("dt a span.value").html();
    }

    $('body').bind('click', function(e) {
        var $clicked = $(e.target);
        if (! $clicked.parents().hasClass("dropdown")){
            $(".dropdown dd ul").hide();
        }
    });
}
function tabOnMouseEnter()
{
   var $parent = $(this).parent('li');
   var bck = $parent.css('background-image');
   $parent.css('background-image',bck.replace('.png','_hover.png'));
   $(this).animate({ width: 175+'px' }, 150);
}
function tabOnMouseLeave()
{
    var $parent = $(this).parent('li');
    var bck = $parent.css('background-image');
    $parent.css('background-image',bck.replace('_hover',''));
    $(this).animate({ width: 135+'px' }, 150);
}
function currentTab(slug,w){
    var tabMaxWidth = w || 175;
    var menuMap = {
        lifestyle:{tab:'#tab_lifestyle',color:'#CC0066'},
        business:{tab:'#tab_business',color:'#990000'},
        'science-e-technology':{tab:'#tab_science',color:'#006600'},
        entertainment:{tab:'#tab_entertainment',color:'#FF6600'},
        sport:{tab:'#tab_sport',color:'#CCCC00'},
        jamming:{tab:'#tab_jamming',color:'#660066'},
        italy:{tab:'#tab_italy',color:'#0099CC'},
        world:{tab:'#tab_world',color:'#006699'}
    }
    if(typeof menuMap[slug] !== 'undefined'){
        var $tabLi = $(menuMap[slug].tab);
        var $tabA = $('a',menuMap[slug].tab);
        var bck = $tabLi.css('background-image');
        if(bck.search(/_hover/) === -1){
           $tabLi.css('background-image',bck.replace('.png','_hover.png'));
           $tabA.css('background-color',menuMap[slug].color);
           $tabA.css('width',tabMaxWidth+'px');
           $tabA.unbind('mouseenter',tabOnMouseEnter);
           $tabA.unbind('mouseleave',tabOnMouseLeave);

         }
     }
}

$(function(){
    $('.ratingblock').tooltip({
      track: true,
      delay: 0,
      showURL: false,
      showBody: " - ",
      extraClass: "videoRatingTooltip"
      /*top: -15,
      left: 5*/
    });

   if($('#searchWithinTheChannel').length > 0){
        tvnDropDownMenu();
    }
  
    $('#query').focus(function(){
        $(this).val('');
    });
    $('#query').blur(function(){
        var query = $(this).val();
        var val = (query.length > 0) ? query : 'Search';
        $(this).val(val);
    });

   $('#frmQuickSearch').submit(function () { return false; }); // so it won't submit
    $('#frmQuickSearch').keypress(function(e) {
        if (e.which == 13) {
          return false;
        }
    });
    /* Quick Search */
    $("#searchButton").click(function () {
        var $frmQuickSearch = $('#frmQuickSearch');
        var channel = $("#result").text();
        var action = $frmQuickSearch.attr('action');
        var query = (channel.length > 0) ? urlencode(strip_tags($('#query').val())) + '/channel/' + urlencode(strip_tags(channel)) : urlencode(strip_tags($('#query').val()));
        $frmQuickSearch.attr('action',action+'/'+query);
        $frmQuickSearch.unbind('submit');
        $frmQuickSearch.submit();
        
    });
    /* Menu */
    $('.slidingElement li').each(function(){
        var bck = $(this).css('background-image');
        $(this).css('background-image',bck.replace('.png','_hover.png'));
    });
   $('.slidingElement li').each(function(){
        var bck = $(this).css('background-image');
        $(this).css('background-image',bck.replace('_hover',''));
    });
    
    $('.slidingElement li a')
        .bind('mouseenter',tabOnMouseEnter)
        .bind('mouseleave',tabOnMouseLeave);
       
});



