var ie = (function(){

    var undef,
        v = 3,
        div = document.createElement('div'),
        all = div.getElementsByTagName('i');

    while (
        div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
        all[0]
    );

    return v > 4 ? v : undef;

}());

if(ie < 11){
    jQuery.support.cors = true;
    console.log('ie 10 and below detected');
}
var lst=0;
function applyEllipse(criteria) {
    //applying ellipses
    $(criteria).each(function(index) {
        var $text = $(this).find('div');
        var originalText = htmlEntitiesDecode($text.data('title'));
        $text.html(originalText);
        var temp = originalText;

        if ($(this).outerHeight() < $text.outerHeight()) {

            while ($(this).outerHeight() < $text.outerHeight()) {
                $text.text(temp = temp.substr(0, temp.length - 1));
            }
            $text.text(temp = temp.substr(0, temp.length - 3));
            $text.append('...');
        }
    });
}


function convertToSlug(Text)
{
    return Text
            .toLowerCase()
            .replace(/ /g, '-')
            .replace(/[^\w-]+/g, '')
            ;
}
/*
function addLink() {
    var selection = window.getSelection();
    selection2 = selection.toString();
    var htmlDiv = document.createElement("div");
    for (var i = 0; i < selection.rangeCount; ++i) {
        htmlDiv.appendChild(selection.getRangeAt(i).cloneContents());
    }
    var selectionHTML = htmlDiv.innerHTML;

    var pagelink = "<br/><br/>More from: " + document.URL + " <br/>";
    var copytext = selectionHTML + pagelink;

    var newdiv = document.createElement('div');
    newdiv.style.position = 'absolute';
    newdiv.style.left = '-99999px';

    document.body.appendChild(newdiv);
    newdiv.innerHTML = copytext;
    if (selection2.indexOf('iframe') > 0) {
        selection.selectAllChildren(selection2);
    } else {
        selection.selectAllChildren(newdiv);
    }
    window.setTimeout(function() {
        document.body.removeChild(newdiv);
    }, 0);
}
document.oncopy = addLink;*/

$(function() {
    $(document).on("mouseover", ".fb_icon", function(){
        $(this).attr("src", assets_url + "img/social_media_icons/fb_hover_colored.png");
    });
    $(document).on("mouseout", ".fb_icon", function(){
        if(!$(this).hasClass("smiblack")){
            $(this).attr("src", assets_url + "img/social_media_icons/fb_share_idle.png");
        } else {
            $(this).attr("src", assets_url + "img/social_media_icons/d_fb_share_idle-copy.png");
        }
    });
    $(document).on("mouseover", ".tweet_icon", function(){
        $(this).attr("src", assets_url + "img/social_media_icons/tweet_hover_colored.png");
    });
    $(document).on("mouseout", ".tweet_icon", function(){
        if(!$(this).hasClass("smiblack")){
            $(this).attr("src", assets_url + "img/social_media_icons/tweet_idle.png");
        } else {
            $(this).attr("src", assets_url + "img/social_media_icons/d_tweet_idle-copy.png");
        }
    });
    $(document).on("mouseover", ".insta_icon", function(){
        $(this).attr("src", assets_url + "img/social_media_icons/insta_hover_colored.png");
    });
    $(document).on("mouseout", ".insta_icon", function(){
        if(!$(this).hasClass("smiblack")){
            $(this).attr("src", assets_url + "img/social_media_icons/insta_share_idle.png");
        } else {
            $(this).attr("src", assets_url + "img/social_media_icons/d_insta_share_idle-copy.png");
        }
    });
    $(document).on("mouseover", ".viber_icon", function(){
        $(this).attr("src", assets_url + "img/social_media_icons/viber_share_hover_colored.png");
    });
    $(document).on("mouseout", ".viber_icon", function(){
        if(!$(this).hasClass("smiblack")){
            $(this).attr("src", assets_url + "img/social_media_icons/viber_share_idle.png");
        } else {
            $(this).attr("src", assets_url + "img/social_media_icons/d_viber_share_idle-copy.png");
        }
    });
    $(document).on("mouseover", ".yt_icon", function(){
        $(this).attr("src", assets_url + "img/social_media_icons/youtube_share_hover_colored.png");
    });
    $(document).on("mouseout", ".yt_icon", function(){
        if(!$(this).hasClass("smiblack")){
            $(this).attr("src", assets_url + "img/social_media_icons/youtube_share_idle.png");
        } else {
            $(this).attr("src", assets_url + "img/social_media_icons/d_youtube_share_idle-copy.png");
        }
    });
    $(document).on("mouseover", ".rss_icon", function(){
        $(this).attr("src", assets_url + "img/social_media_icons/rss_share_hover_colored.png");
    });
    $(document).on("mouseout", ".rss_icon", function(){
        if(!$(this).hasClass("smiblack")){
            $(this).attr("src", assets_url + "img/social_media_icons/rss_share_idle.png");
        } else {
            $(this).attr("src", assets_url + "img/social_media_icons/d_rss_share_idle-copy.png");
        }
    });

    $(".smLogin").on("click", function(){
        $(".navbar-collapse").removeClass("in");
    });
    $("#gno_burger .btn")
            .mouseover(function() {
                $(this).css("background-color","#fff");
                $("button .icon-bar").css("background-color","#cc0001");

            })
            .mouseout(function() {
                $(this).css("background-color","#cc0001");
                $("button .icon-bar").css("background-color","#fff");

            });

    if($(window).width() < 768){
        $(".mobile-leaderboard, .mobile-mrec").show();
    }

});

$(document).on("click", ".register, #btnLogin", function ( e ) {
	/*google analytics send*/
	if($(this).attr("id") != "btnLogin"){
		var params = {event_category:"register", event_label:"clicked register from page:"+document.title, event_value:1};
	}
	else{
		var params = {event_category:"login", event_label:"clicked login from page:"+document.title, event_value:1};
	}
	CUSTOM_ANALYTICS.ga_click_event(params);
	/*end*/
});

function restore_default_meta(){
    /* Set all meta tags to default useful when closing preview and theater mode for both photo and video.*/
    console.log(original_title);
    var page = document.URL.split('/');
    var t = page[4].capitalizeFirstLetter() + " │ GMA News Online";
    var url = base_url + page[4];

    $("meta[property='twitter\\:card']").attr("content", "summary_large_image");
    $("meta[property='twitter\\:player']").attr('content', "");
    $("meta[property='twitter\\:app:url:iphone']").attr('content', "");
    $("meta[property='twitter\\:app:url:ipad']").attr('content', "");
    $("meta[property='twitter\\:app:url:googleplay']").attr('content', "");

    $("meta[property='og\\:title'], meta[property='twitter\\:title']").attr("content",t);
    $("meta[property='og\\:url'], meta[property='twitter\\:url']").attr("content", url);
    $("link[rel='canonical']").attr('href', url);
    $("meta[property='og\\:image'], meta[property='twitter\\:image'], meta[property='thumbnail']").attr("content", 'http://images.gmanews.tv/webpics/2015/10/default_new_2015_10_12_15_40_12.jpg');
    $("meta[property='twitter\\:description']").attr("content", 'Home of GMA News Online listing top breaking Philippine and international headlines, '
          + 'videos and photos encompassing sections of current events, sports, economy and business, science & technology, pinoy abroad, showbiz entertainment, '
          + 'lifestyle, weather, traffic and local region stories. Also includes foreign exchange rates, lotto results, board exam results.');
    $("meta[property='og\\:description'], meta[name='description']").attr("content", 'Home of GMA News Online listing top breaking Philippine and international headlines, '
          + 'videos and photos encompassing sections of current events, sports, economy and business, science & technology, pinoy abroad, showbiz entertainment, '
          + 'lifestyle, weather, traffic and local region stories. Also includes foreign exchange rates, lotto results, board exam results.');
}

String.prototype.capitalizeFirstLetter = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

function formatAMPM(date) {
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var ampm = hours >= 12 ? 'PM' : 'AM';
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    minutes = minutes < 10 ? '0' + minutes : minutes;
    var strTime = hours + ':' + minutes + ampm;
    return strTime;
}

function is_mystream(widget_container) {

    var mystream = false;
    var parent_widget = $(widget_container).parent().parent();
    if (parent_widget.hasClass("default_stream_container")) {
        mystream = true;
    }

    return mystream;

}

function currtime() {
    d = new Date();
    s = (d + "").split(" ");
    date = s[1] + " " + s[2] + ", " + s[3];
    h = d.getHours();
    m = d.getMinutes();
    DayNight = "PM";
    if (h < 12)
        DayNight = "AM";
    if (h > 12)
        h = h - 12;
    if (m <= 9)
        m = "0" + m;

    $("#date").text(date);

    $("#time").text(h + ":" + m + " " + DayNight + " " + s[5]);
}
;

var d, h, m, s, DayNight;
var original_title;
var original_url = document.location.href;
currtime();

var scrollClose = function() {
    $('#burger_dropdown').slideUp(100);
};
$(document).ready(function() {
    setInterval(currtime, 1000);
    $(document).mouseup(function (e){
        var container = $("#burger_dropdown");
        if (!container.is(e.target) && container.has(e.target).length === 0 && e.target.className != 'icon-bar' && e.target.className != 'btn dropdown-toggle'){
            container.hide();
        }
    });

    $(window).resize(function(){
      if($(window).height() > 600 && $(window).width() > 768 ){
          $(".dropdown-menu").removeClass("scrollable-menu");
      }else{
          $('.scrollable-menu').css('max-height', (($(window).height()-10)-$('header').height())-20);
      }
    });

    $("#srchGno_small").on('focusin focus', function(e){
      // e.preventDefault();
      // e.stopPropagation();
      $(document).unbind('DOMMouseScroll mousewheel', scrollClose);
      $(document).unbind('scroll', closeBurger);
      setTimeout(function(){
        $(document).on('DOMMouseScroll mousewheel', scrollClose);
        $(document).on('scroll', closeBurger);
      }, 2000);
    })
    var closeBurger = function(){
      $('#burger_dropdown').hide();
    }
    $(document).on('scroll', closeBurger);
    $(document).scroll(function() {

        $('.navbar').finish();
        $('.redline').finish();


        if (45 < $(window).scrollTop()) {

            $('.navbar').slideUp("fast");
            $('.redline').fadeIn("fast", function() {
            $(".social_media_icons").fadeIn("slow");

                // Animation complete


				if (window_width>=480) {
					//window width is at least 500px
					$('#gno_navigation > ul.dropdown-menu').css("top","48px");
				}
				else {
					//window width is less than 500px
					$('#gno_navigation > ul.dropdown-menu').css("top","51px");
				}
            });


        } else {

            $('.navbar').slideDown("slow");
			$('.redline').fadeOut("fast", function() {
            $(".social_media_icons").fadeOut("slow");
                // Animation complete

				if (window_width>=480) {
					//window width is at least 500px
					$('#gno_navigation > ul.dropdown-menu').css("top","43px");
				}
				else {
					//window width is less than 500px

					$('#gno_navigation > ul.dropdown-menu').css("top","46px")
				}


            });


        }




    });

    $('.srchBtn').on('click', function() {
        if ($('#itemContent1').attr('class') == "closed") {
            $('#itemContent1').attr('class', 'opened');
            $('#itemContent1').slideDown('fast');
            if($(window).width()<768)
                document.srchform_small.q.focus();
            else
                document.srchform.q.focus();
        } else {
            $('#itemContent1').attr('class', 'closed');
            //$('#itemContent1').hide();
            $('#itemContent1').slideUp('fast');
        }
    });

    $(".dropdown").on('hide.bs.dropdown', function (e) {
        $(this).find("span.caret").css({"-ms-transform": "","-webkit-transform": "","transform": ""});
    });
    $(".dropdown").on('show.bs.dropdown', function (e) {
        $(this).find("span.caret").css({"-ms-transform": "rotate(180deg)","-webkit-transform": "rotate(180deg)","transform": "rotate(180deg)"});
    });
    $(".mCaret").on('click', function (e) {
        if(!$(this).hasClass('collapsed')){
            $(this).find("span.caret").css({"-ms-transform": "","-webkit-transform": "","transform": ""});
        } else {
            $(this).find("span.caret").css({"-ms-transform": "rotate(180deg)","-webkit-transform": "rotate(180deg)","transform": "rotate(180deg)"});
        }
    });

    /*$(".dropdown-toggle").on('click', function(){
        console.log($(this).parent().hasClass("dropdown open"));
        if($(this).parent().hasClass("dropdown open")){
            $("span.caret").css({"-ms-transform": "rotate(180deg)","-webkit-transform": "rotate(180deg)","transform": "rotate(180deg)"});
        } else {
            $("span.caret").css({"-ms-transform": "","-webkit-transform": "","transform": ""});
        }
    });*/


});
