var userLocation;

$(document).ready(function () {

    userLocation = getGeoLocation();

    clockUpdater();
    setInterval('clockUpdater()', 5000);

    if (window.IsLoggedIn && IsLoggedIn()) {
        $(".navigation .item a[href='/page/secure/MyAccount']").show();
    } else {
        $('.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');
    }

    if (GLOBAL_PAGE_BASE_PATH == '/WatchLive') {

        var embedURL;

        if (window.IsLoggedIn && IsLoggedIn()) {
            embedURL = "/page/elements/html/Home/0,," + GLOBAL_SITE_ID + "~226~10474,00.html";
        } else {
            embedURL = "/page/elements/html/Home/0,," + GLOBAL_SITE_ID + "~226~10475,00.html";
        }

        $.ajax({
            url: embedURL,
            async: false,
            dataType: "html",
            success: function (data) {
                $(".watchLivePage").html(data);
            }
        });

        $('.schedule').css('height', '235px');

    } else if (GLOBAL_PAGE_BASE_PATH == '/Home') {
        $('.teaserArticle').css('margin-top', '20px');
    }
    
	if ( $('#eventCarousel li').length > 1 ) {
		startCarousel('eventCarousel');
	}

    convertTime();
    

    $(".koTime .countdown").each(function (index, elem) {
        
        $(this).countdown({
		  type: "dates",
		  endDate: $(this).html(),
		  zeroCallBack: function(){
		    //location.reload();
		  }
		});
    });


});

function startCarousel(id) {

    $('#' + id).jcarousel({
        auto: 10,
        wrap: 'circular',
        scroll: 1,
        initCallback: evcarousel_initCallback
    });

}

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;}} #close{display:block;padding-bottom: 50px;}</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.
*/

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;
    }

    // TODO: FIX IF USING PAGINATION TO KEEP SEARCH TERM
    if (!form) {
        searchTerm = "";
    } else {
        searchTerm = $.trim(form.freetext.value) + "*";
    }

    $.ajax({
        url: "/siteSearch/siteSearch/0,," + GLOBAL_SITE_ID + ",00.html?iTypeIds=36&36filterIn_videoTypeId=714,738&36filterIn_clipCategoryId=18236,18239&sortf=publishedDate&pageSize=" + pageSize + "&pageNumber=" + page + "&gXsltId=" + gXsltId + "&freetext=" + searchTerm,
        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");

    if (GLOBAL_PAGE_BASE_PATH.indexOf("/CatchUpVideo") != -1) {
        // Scroll down page to show results
        $('html,body').animate({
            scrollTop: $("#results").offset().top
        }, 'slow');
    }

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

}

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 + ' - ' + eventDate + suffix + ' ' + eventMonth;
            }
        } else if (noDays == 1) {
           outputDate = eventHrs + ':' + eventMins + ' - ' + eventDate + suffix + ' ' + eventMonth;
        } else {
            outputDate = eventHrs + ':' + eventMins + ' - ' + eventDate + suffix + ' ' + eventMonth;
        }

        $(this).text(outputDate);
    })
}
