var geoLocation;

$(document).ready(function () {
    	
	if (window.IsLoggedIn && IsLoggedIn()) {
		$('.loggedIn').show();
		$('.loggedOut').hide();
        $(".navigation .item a[href='/page/secure/MyAccount']").show();
    } else {
		$('.loggedOut').show();
		$('.loggedIn').hide();
        $('.subscription').show();
        $(".subscribe").html('<div class="greenBtn"><div class="greenBtnLeft"><a href="/page/secure/loginOrCreateAccount">Subscribe now</a></div><div class="greenBtnRight"></div></div> or <a href="/page/loginOrBuy">sign in</a> to watch');
    }

    
	carouselLength = $('#eventCarousel li').length;
	if (carouselLength == 1 ) {
		initSingleCarousel();
	} else if ( carouselLength > 1 ) {
		startCarousel('#eventCarousel');
	} 

});

function updateClock() {
	var timeNow = new Date();
	$('#headerLocation p span').html(timeNow.format('HH:MM'));
}

function equalHeight(group) {
	var tallest = 0;
	group.each(function() {
		var thisHeight = $(this).height();
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	group.height(tallest);
}

function initSingleCarousel(){
	var daysLabel = "days";
	var hoursLabel = "hours";
	var minsLabel = "mins";
	var secsLabel = "secs";
	//init countdowns
	var endDateVal = $('.countdown:visible').children("ul").attr("class");
	$('.countdown:visible').countdown({endDate: endDateVal, days: daysLabel, hours: hoursLabel, mins: minsLabel, secs: secsLabel});
}

function startCarousel(wrapper) {
	var daysLabel = "days";
	var hoursLabel = "hours";
	var minsLabel = "mins";
	var secsLabel = "secs";

	$(wrapper+':visible').jcarousel({ //only start carousel if its visible
		auto: 10,
		wrap: 'circular',
		scroll: 1,
		initCallback: evcarousel_initCallback,
		itemVisibleInCallback: function(carousel, li, index, state){
			endDateVal = $(li).find('.countdown').children("ul").attr("class");
			if(endDateVal){
				$(li).find('.countdown').countdown({endDate: endDateVal, days: daysLabel, hours: hoursLabel, mins: minsLabel, secs: secsLabel});
			}
		}
	});
}

function startMiniCarousel(wrapper) {
	$(wrapper+':visible').jcarousel({ //only start carousel if its visible
		auto: 3,
		wrap: 'circular',
		vertical: true,		
		scroll: 2,
		initCallback: evcarousel_initCallback,
		itemVisibleInCallback: function(carousel, li, index, state){
			endDateVal = $(li).find('.countdown').children("ul").attr("class");
			if(endDateVal){
				$(li).find('.countdown').countdown({endDate: endDateVal, days: daysLabel, hours: hoursLabel, mins: minsLabel, secs: secsLabel});
			}
		}
	});
}

function clockUpdater() {
	var theDate = new Date();

	var htmlContent = userLocation.name + ' / ';
	htmlContent += theDate.format('HH:MM');
	$('#userLocation').html(htmlContent);
}

function evcarousel_initCallback(carousel) {
	// Disable autoscrolling if the user clicks the prev or next button.
	carousel.buttonNext.bind('click', function () {
		carousel.startAuto(0);
	});
	carousel.buttonPrev.bind('click', function () {
		carousel.startAuto(0);
	});

	// Pause autoscrolling if the user moves with the cursor over the clip.
	carousel.clip.hover(function () {
		carousel.stopAuto();
	}, function () {
		carousel.startAuto();
	});
} 

function expandCollapse(num, logic) {
    var query = document.getElementById("q_" + num);
    if (!query) return true;
    if (logic || query.style.display == "none" || query.style.display == "") {
        $(query).show();
    } else {
        $(query).hide();
    }
    return false;
}

function printElement(element) {
    if ((element != "") && (element != null)) {
        w = window.open();
        w.document.write('<style>@media print{#close{display: none;}} .scheduleTable table {border-collapse:collapse;} #close{display:block;padding-bottom: 50px;} </style>');
		w.document.write('<style>@import url("/style/0,,'+GLOBAL_SITE_ID+'~38086,00.css"); </style>');		
		w.document.write('<style>body {background: #fff;} </style>');
        w.document.write('<a href="#" id="close" onclick="window.close()"> Close this window</a>');
        w.document.write($(element).html());
        w.print();
        //w.close();
    }
}

function getPopOut() {
   /*var width = $('.articleVideo').width();
   var height = $('.articleVideo').height();
   var popOut = window.open('','','width='+width+',height='+height+'');*/
   var popOut = window.open();
   if(GLOBAL_PAGE_BASE_PATH =='/CatchUpVideo') {
       alert($('.videoSearch').html());
       popOut.document.write('<style>body{padding:0;margin:0;}form,#results,.videoInfo{display:none;}</style>');
       popOut.document.write($('.videoSearch').html());
   } else {
    alert($('.columnOne').html());
       popOut.document.write('<style>body{padding:0;margin:0;}.videoTitle{display:none;}</style>');
       popOut.document.write($('.columnOne').html());
   }
}

function equalHeight(group) {
	var tallest = 0;
	group.each(function() {
		var thisHeight = $(this).height();
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	group.height(tallest);
}

/*
    VOD Search Functionality
    Same function is used for search, pagination and listing videos.
*/

// VOD - Sites that use modified lucene calls.
var siteInfo = new Array();
// AFC Cup - www.liveafc.tv
siteInfo[13585] = new Array();
siteInfo[13585][0] = '19620o14047'; // CategoryID 
siteInfo[13585][1] = 912; // Default video type ID

// A League - www.livealeague.tv
siteInfo[13102] = new Array();
siteInfo[13102][0] = 14038; // CategoryID 
siteInfo[13102][1] = 734; // Default video type ID

// J League - www.livejleague.tv
siteInfo[13091] = new Array();
siteInfo[13091][0] = 14039; // CategoryID
siteInfo[13091][1] = 878; // Default video type ID

// Chinese Super League - www.livecsl.tv
siteInfo[13127] = new Array();
siteInfo[13127][0] = 14042; // CategoryID 
siteInfo[13127][1] = 906; // Default video type ID

// Live fight Code
siteInfo[13563] = new Array();
siteInfo[13563][0] = ''; // CathegoryID 
siteInfo[13563][1] = 873; // Default video type ID - Videos
siteInfo[13563][2] = 872; // Default video type ID - Fullfights page

function loadVOD(form, page) {

    var pageSize;
    var searchTerm;
    var gXsltId = 1259;

    $(".results").css("display", "none");
    $(".loader").css("display", "block");

    if (GLOBAL_PAGE_BASE_PATH == "/Home") {
        pageSize = 6;
    } else if (GLOBAL_PAGE_BASE_PATH.indexOf("/CatchUpVideo") != -1) {
        pageSize = 8;
    } else {
        pageSize = 20;
    }

    if (!form) {
        searchTerm = $('input[name="freetext"]').eq(0).val();
    } else {
        $(".articleVideo").css("display", "none");
        searchTerm = $.trim(form.freetext.value) + "*";
        $('input[name="freetext"]').val($.trim(form.freetext.value));
    }
	// remove ^,|,\ from search term to prevent search error
	searchTerm=searchTerm.replace(/\\|\/|\||\^/g,"");

	var luceneCall = "";
    if (GLOBAL_SITE_ID == "13585" || GLOBAL_SITE_ID == "13102" || GLOBAL_SITE_ID == "13091" || GLOBAL_SITE_ID == "13127") {
        luceneCall = "/siteSearch/siteSearch/0,," + GLOBAL_SITE_ID + ",00.html?iTypeIds=36&36filterOut_videoTypeId=737,"+ siteInfo[GLOBAL_SITE_ID][1] +"&36filterIn_clipCategoryId="+ siteInfo[GLOBAL_SITE_ID][0] +"&sortf=publishedDate&pageSize=" + pageSize + "&pageNumber=" + page + "&gXsltId=" + gXsltId + "&freetext=" + searchTerm;
    }
    else {
        var vodType = "";
    
		if (GLOBAL_SITE_ID == "13563" && (GLOBAL_PAGE_ID == "2294492" || GLOBAL_PAGE_ID == "2294493")) {  // fightcode \CatchUp or \CatchUpVideo
			vodType = ","+siteInfo[GLOBAL_SITE_ID][1];
		}
		else if (GLOBAL_SITE_ID == "13563" && (GLOBAL_PAGE_ID == "2294616" || GLOBAL_PAGE_ID == "2294617")) {  // fightcode  \FullFights or \FullFightsVideo
			vodType = ","+siteInfo[GLOBAL_SITE_ID][2];
		}

		luceneCall = "/siteSearch/siteSearch/0,," + GLOBAL_SITE_ID + ",00.html?iTypeIds=36&36filterOut_videoTypeId=737" + vodType + "&sortf=publishedDate&pageSize=" + pageSize + "&pageNumber=" + page + "&gXsltId=" + gXsltId + "&freetext=" + searchTerm;
    }

    $.ajax({
        url: luceneCall,
        async: false,
        cache: false,
        dataType: "html",
        success: vodSuccess,
        error: vodError
    });

    return false;

}

function vodSuccess(data) {

    if (data.indexOf('Invalid request') != -1) {
        data = '<div class="empty">Sorry, no results found</div>';
    }

    $(".loader").css("display", "none");
    $(".results").css("display", "block");

    $("#results").html(data);

    $(".teaser .title a, .videoTeaser a").each(function() { 
        $(this).attr('href', $(this).attr('href')+'?freetext=' + $('input[name="freetext"]').eq(0).val());
    });
}

function vodError() {
    $(".loader").css("display", "none");
    $(".results").css("display", "block");
    $("#results").html('<div class="empty">Error loading content, please refresh the page.</div>');
}

/*
    Localisation script for converting time to local clock.
    Event time is GMT.
*/


//Function converts ISODate string into a format that all browsers (inc Fing! IE6) will accept.

function parseISODateString(dateString) {
    var Zp = (dateString.charAt(10) == "T") ? 19 : 10;
    var xDate = new Date(dateString.substr(0, Zp).replace(/-/g, '/').replace("T", " "));
    if (dateString.length > Zp) {
        xDate.setMinutes(xDate.getMinutes() + xDate.getTimezoneOffset());
        if (dateString.charAt(Zp) != "Z") {
            var tZ = dateString.substr(Zp).split(":");
            tZ = tZ[0] * 60 + (tZ[1] * 1);
            xDate.setMinutes(xDate.getMinutes() + tZ);
        }
    }
    return xDate;
}

//Function returns number of days in month

function daysInMonth(iYear, iMonth) {
    return 32 - new Date(iYear, iMonth, 32).getDate();
}


//Function to identify the date of the last Sunday of a passed month.
// accepts
// .getMonth() value. eg: Jan = 0 and Dec = 11.
// .getYear() value

function getLastSunday(year, month) {
    //Calculate days in month
    var j = daysInMonth(year, month);
    while (j >= 1) {
        var myDate = new Date(year, month, j);
        // '0' value represents Sunday - value ruturned from .getDay() method.
        if (myDate.getDay() == 0) {
            //exit loop and return date
            return myDate;
        }
        //decrement loop
        j += -1;
    }
}

// Extend date object to display month names
Date.prototype.getMonthName = function () {
    var m = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    return m[this.getMonth()];
}

// Extend date object to display date suffix
Date.prototype.getSuffix = function () {
    var suffix;
    var eventDate = this.getDate();
    // Add suffix to date (1st, 2nd, 4th, etc.)
    if (eventDate == 1) suffix = ("st");
    else if (eventDate == 2) suffix = ("nd");
    else if (eventDate == 3) suffix = ("rd");
    else if (eventDate == 21) suffix = ("st");
    else if (eventDate == 22) suffix = ("nd");
    else if (eventDate == 23) suffix = ("rd");
    else if (eventDate == 31) suffix = ("st");
    else suffix = ("th");
    return suffix;
}

function convertTime() {
    //Create new local date variable
    var localDateTime = new Date();
    //Calculate Local Time Zone Offset
    var timeZoneOffset = localDateTime.getTimezoneOffset() * 60000;


    //Calculate Curent Year
    var year = localDateTime.getFullYear();
    //Calculate Curent Month
    var month = localDateTime.getMonth();
    //Calculate Current Day
    var day = localDateTime.getDate();

    // Calculate last Sunday of Mar (British Summer Time Begins)
    var daylightSavingsBegin = getLastSunday(year, 2);
    // Calculate last Sunday of Oct (British Summer Time Ends)
    var daylightSavingsEnd = getLastSunday(year, 9);

    $('.startTime').each(function () {
        var eventTime = $(this).html();
        var isoDateTime = eventTime.substring(0, 19);

        //Passer required as ie6 cannot translate raw isoDateTime
        var convertedDate = new Date(parseISODateString(isoDateTime));

        var localEventTimeSeconds = convertedDate.getTime();

        var adjustedEventDateSeconds = localEventTimeSeconds - timeZoneOffset;
        var adjustedEventDateTime = new Date(adjustedEventDateSeconds);
        var localTimeSeconds = localDateTime.getTime();

        var eventDate = adjustedEventDateTime.getDate();
        var suffix = adjustedEventDateTime.getSuffix();
        var eventMonth = adjustedEventDateTime.getMonthName();
        var eventMonthInt = adjustedEventDateTime.getMonth();
        var eventDay = adjustedEventDateTime.getDay();
        var eventYear = adjustedEventDateTime.getFullYear();
        var eventHrs = adjustedEventDateTime.getHours();
        var eventMins = adjustedEventDateTime.getMinutes();

        var eventDateString = '';
        var localTimeDateString = '';

        eventDateString = eventYear + '/' + eventMonthInt + '/' + eventDate;
        localTimeDateString = year + '/' + month + '/' + day;

        //Set 1 day in milliseconds
        var one_day = 1000 * 60 * 60 * 24
        var noDays = Math.floor((adjustedEventDateSeconds - localTimeSeconds) / (one_day));

        if (eventHrs < 10) {
            eventHrs = "0" + eventHrs
        }


        if (eventMins < 10) {
            eventMins = "0" + eventMins
        } /* */

        if (noDays == 0) {
            if (eventDateString === localTimeDateString) {
                outputDate = eventHrs + ':' + eventMins + ' Today';
            }
            else {
                outputDate = eventHrs + ':' + eventMins + ' Tomorrow';
            }
        } else if (noDays == 1) {
            outputDate = eventHrs + ':' + eventMins + ' Tomorrow';
        } else {
            outputDate = eventHrs + ':' + eventMins + ' - ' + eventDate + suffix + ' ' + eventMonth;
        }

      //    outputDate = eventHrs + ':' + eventMins + ' - ' + eventDate + suffix + ' ' + eventMonth;
        $(this).text(outputDate);
    })
}
function loadVODFilter(form, page, categoryId) {
    var pageSize;
    var searchTerm;
    var gXsltId = 1259;
    var categoryString = "";
	
	if (categoryId==="0") {
        categoryString = "";
    }else {
		categoryString='&36filterIn_clipCategoryId=' + categoryId;
	}
    $(".results").css("display", "none");
    $(".loader").css("display", "block");
    if (GLOBAL_PAGE_BASE_PATH == "/Home") {
        pageSize = 6;
    } else if (GLOBAL_PAGE_BASE_PATH.indexOf("/CatchUpVideo") != -1) {
        pageSize = 8;
    } else {
        pageSize = 20;
    }

    if (!form) {
        searchTerm = $('input[name="freetext"]').eq(0).val();
    } else {
        $(".articleVideo").css("display", "none");
        searchTerm = $.trim(form.freetext.value) + "*";
        $('input[name="freetext"]').val($.trim(form.freetext.value));
    }

	var luceneCall = "/siteSearch/siteSearch/0,," + GLOBAL_SITE_ID + ",00.html?iTypeIds=36&36filterOut_videoTypeId=737" + categoryString + "&sortf=publishedDate&pageSize=" + pageSize + "&pageNumber=" + page + "&gXsltId=" + gXsltId + "&freetext=" + searchTerm;
    if (GLOBAL_SITE_ID == "13585" || GLOBAL_SITE_ID == "13102" || GLOBAL_SITE_ID == "13091" || GLOBAL_SITE_ID == "13127") {
        luceneCall = "/siteSearch/siteSearch/0,," + GLOBAL_SITE_ID + ",00.html?iTypeIds=36&36filterOut_videoTypeId=737,"+ siteInfo[13127][1] + categoryString + "&sortf=publishedDate&pageSize=" + pageSize + "&pageNumber=" + page + "&gXsltId=" + gXsltId + "&freetext=" + searchTerm;
    }
    
    $.ajax({
        url: luceneCall,
        async: false,
        cache: false,
        dataType: "html",
        success: vodSuccess,
        error: vodError
    });
    return false;
}

function getParameterByName( param )
{
  var name = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}
