(function(SinemaTv, $) {
    SinemaTv.guideReminder = {};


    //hold xhr cache
    var remindCacheData = {};


    var setNextRemindTimes = function(response, infoBox, parentContainer){
        var remindTimeSelect = infoBox.find("select.remindTime"); 

        infoBox.find("select.remindPeriod option:first").attr("selected","selected");
        
        //TODO: i18n
        var noSuchRemindTime = "Hatırlatılacak gün yok";

        infoBox.find(".fancySelectContainer").remove();
        remindTimeSelect.find("option").remove();

        if(response && response.length > 0){
            for(var i = 0; i < response.length; i++){
                var dateFormatted = SinemaTv.util.formatDateFromTimestamp( response[i],"%d %M %Y - %H:%i");
                $("<option>").val(response[i]).html(dateFormatted).appendTo(remindTimeSelect);
            }
        }
        else {
            //TODO: should we display remindbox?
            $("<option>").val("0").html(noSuchRemindTime).appendTo(remindTimeSelect);
        }

        SinemaTv.ui.initFancySelect(parentContainer);
    };

    /**
     * Get next guide times for given filmId and timeOffset
     */
    var getNextGuideTimes = function(filmId, timeOffset, infoBox, parentContainer){
        var url = SinemaTv.core.getRootPath() + "guide/next-dates";
        var getData = {"filmId" : filmId, "timeOffset" : timeOffset};
        var cacheKey = filmId + "_" + timeOffset;

        
        if( !remindCacheData[cacheKey] ) {
            $.getJSON( url , getData, function(response){
                remindCacheData[cacheKey] = response;
                setNextRemindTimes(remindCacheData[cacheKey], infoBox, parentContainer);
            });
        }
        else {
            setNextRemindTimes(remindCacheData[cacheKey], infoBox, parentContainer);
        }
    };



    var submit = function(guideId, remindPeriod, email, container){

        var reminderNotification = container.find(".reminderNotification");
        var showTimer;


        clearTimeout(showTimer);
        reminderNotification.find("div").hide();


        Alarm.add('', guideId, remindPeriod, email, function(data){
            if( parseInt(data, 10) > 0 ) {
                reminderNotification.find("div.successNotification").fadeIn(function(){
                    showTimer = setTimeout( function(){
                        reminderNotification.find("div").fadeOut();
                    }, 200000);
                });
            }
            else {
                reminderNotification.find("div.processFailed").fadeIn(function(){
                    showTimer = setTimeout( function(){
                        reminderNotification.find("div").fadeOut();
                    }, 2000);
                });
            }
        }); 
    }; 



    SinemaTv.guideReminder.getNextGuideTimes = getNextGuideTimes;
    SinemaTv.guideReminder.submit = submit;

})(SinemaTv, jQuery);

