/**
 * @author EvgeniyV
 */

ASXLoader = {};

/*
*   Array that stores starttimes of asx entries
*/
ASXLoader.arrayStartTimes = new Array; 

/*
*   Array that stores urls of asx entries
*/
ASXLoader.arrayAsxList = new Array;

/*
*   Array that stores durations of asx entries
*/
ASXLoader.arrayDurations = new Array;

/*
*   Gets or sets current asx entry index
*/
ASXLoader.currentUrlIndex = -1;

/*
*   Callback that runs whe asx file contents getted
*/
ASXLoader.successCallback = null;

ASXLoader.programsDuration = [];

/*
*   Stores value that indicates whether next asx entry exists
*/
ASXLoader.hasNext = true;
ASXLoader.hasPrev = false;

/*
*   Stores value that indicates whether next asx entry exists
*/
ASXLoader.hasPlayList = false;

/*
* Checks whether the current asx entry first 
*/
ASXLoader.isFirst = function(){
    return ASXLoader.currentUrlIndex == 0;
}

/*
* Converts time from HH:mm:ss format to seconds
*/
ASXLoader.convertTime = function(stringTime){
    var arrTime = stringTime.split(":");
    
    var hour = 0;
    var min = 0;
    var sec = 0;
    
    if (arrTime.length > 2)
    {
        hour = parseInt(arrTime[0], 10)*60*60;        
        min = parseInt(arrTime[1], 10)*60;        
        sec = parseInt(arrTime[2], 10);        
    }
    else if (arrTime.length > 1)
    {
        min = parseInt(arrTime[0], 10)*60;        
        sec = parseInt(arrTime[1], 10);        
    }
    else if (arrTime.length > 0)
    {
        sec = parseInt(arrTime[0], 10);        
    }
    
    return sec + min + hour;    
}
      
/*
* Parses xml from $ajax get
*/
ASXLoader.parse = function(xml){
    //init
    count = 0;
    ASXLoader.arrayAsxList = new Array;
    ASXLoader.currentUrlIndex = -1;
    ASXLoader.hasNext = true;
    ASXLoader.arrayStartTimes = new Array;
    ASXLoader.arrayDurations = new Array;

      var i = 0;
     $(xml).find('ENTRY').each(function(){       
     
         $(this).find('REF').each(function(){
            var href = $(this).attr('HREF');
            ASXLoader.arrayAsxList[i] = href;        
        }); 
             
         $(this).find('DURATION').each(function(){
            var duration = $(this).attr('VALUE');
            ASXLoader.arrayDurations[i] = ASXLoader.convertTime(duration);        
        }); 
        
         $(this).find('STARTTIME').each(function(){
            var startTime = $(this).attr('VALUE');
            ASXLoader.arrayStartTimes[i] = ASXLoader.convertTime(startTime);     
        });
        i++;
    }); 
    
    xml = null;
	if (ASXLoader.successCallback && typeof(ASXLoader.successCallback) == "function")
	{
		ASXLoader.successCallback();    
	}
    ASXLoader.hasPlayList = true;
    for (var j = 0 ; j < ASXLoader.arrayAsxList.length; j++)
    {
        Logger.write("href["+j+"]="+ASXLoader.arrayAsxList[j], "ASXLoader");
        Logger.write("duration["+j+"]="+ASXLoader.arrayDurations[j], "ASXLoader");
        Logger.write("starttime["+j+"]="+ASXLoader.arrayStartTimes[j], "ASXLoader");
    }    
}

/*
*   Gets file contents from url
*/
ASXLoader.load = function(url, cb, errorCb){
    ASXLoader.successCallback = cb || function(){};
    $.ajax({
            type: "GET",
            url: url,
            dataType: "xml",
            error: errorCb || function(){},
            timeout: Options.timeout,
            success: ASXLoader.parse});                                       
}

/*
*   Gets starttime for current asx entry 
*/
ASXLoader.getCurrentStartTime = function(){
    ASXLoader.check();
    //Logger.write("[ASXLoader] return start time=" + ASXLoader.arrayStartTimes[ASXLoader.currentUrlIndex], "ASXLoader");
    return ASXLoader.arrayStartTimes[ASXLoader.currentUrlIndex] || 0;
}

/*
*   Sets starttime for current asx entry 
*/
ASXLoader.setCurrentStartTime = function(startTime){
    ASXLoader.check();
    return ASXLoader.arrayStartTimes[ASXLoader.currentUrlIndex] = startTime;
}

/*
*   Gets url for of next entry
*/
ASXLoader.getCurrentUrl = function(){
    ASXLoader.check();
    var result = ASXLoader.arrayAsxList[ASXLoader.currentUrlIndex];    
    return result;
}

/*
*   Gets duration for current asx entry 
*/
ASXLoader.getCurrentDuration = function(){
    ASXLoader.check();
	
	var duration = parseInt(ASXLoader.arrayDurations[ASXLoader.currentUrlIndex], 10);
	duration += parseInt(ASXLoader.arrayStartTimes[ASXLoader.currentUrlIndex], 10);
	duration = duration || 0;
	
    return duration * 1000;
}

/*
*   Gets duration for previous asx entry 
*/
ASXLoader.getPrevDuration = function(){
    ASXLoader.check();    
    var prevDuration = 0;
    for (var i = 0; i < ASXLoader.currentUrlIndex ; i++) {
        var duration = parseInt(ASXLoader.arrayDurations[i], 10) + parseInt(ASXLoader.arrayStartTimes[i], 10);
        prevDuration += duration || 0; 
    }    
    //Logger.write("[ASXLoader] past time="+prevDuration, "ASXLoader");
    return prevDuration;
}

ASXLoader.getTotalDuration = function () {
	ASXLoader.check();
	var totalDuration = 0;
	for (var i = 0; i < ASXLoader.arrayDurations.length; i++) {
		var duration = parseInt(ASXLoader.arrayDurations[i], 10) + parseInt(ASXLoader.arrayStartTimes[i], 10);
        totalDuration += duration || 0; 
	}
	
	return totalDuration * 1000;
}

/*
* Initializes arrays
*/
ASXLoader.check = function(){
    if (!ASXLoader.hasPlayList)
    {
        ASXLoader.arrayStartTimes = new Array; 
        ASXLoader.arrayAsxList = new Array;
        ASXLoader.arrayDurations = new Array;
    }
}

/*
*   Gets url for of next entry
*/
ASXLoader.getNextUrl = function(){
    ASXLoader.hasPlayList = ASXLoader.hasNext;
    ASXLoader.check();
    ASXLoader.currentUrlIndex++;
    Logger.write("[ASXLoader] Get url #" + ASXLoader.currentUrlIndex, "ASXLoader");    
    var result = ASXLoader.hasNext ? ASXLoader.arrayAsxList[ASXLoader.currentUrlIndex] : null;
    ASXLoader.hasNext = ASXLoader.currentUrlIndex + 1 < ASXLoader.arrayAsxList.length;
    ASXLoader.hasPrev = ASXLoader.currentUrlIndex > 0;
    Logger.write("[ASXLoader] Has next entry =" + ASXLoader.hasNext, "ASXLoader");
    return result;
}

/*
*   Gets url for of prev entry
*/
ASXLoader.getPrevUrl = function(){
    ASXLoader.check();
    ASXLoader.hasPrev = ASXLoader.currentUrlIndex > 0;
    ASXLoader.hasPrev ? ASXLoader.currentUrlIndex-- :ASXLoader.currentUrlIndex;
    ASXLoader.hasNext = ASXLoader.currentUrlIndex + 1 < ASXLoader.arrayAsxList.length;
    Logger.write("[ASXLoader] Get url #" + ASXLoader.currentUrlIndex, "ASXLoader");    
    var result = ASXLoader.hasPrev ? ASXLoader.arrayAsxList[ASXLoader.currentUrlIndex] : null;        
    return result;
}

ASXLoader.loadProgramsDuration = function (programs) {
	Logger.write("Loading durations", "ASXLoader", true);
	this.programsDuration = [];
	for (var i = 0; i < programs.length; i++) {
		this.programsDuration[i] = programs[i].length * 60;
		Logger.write("this.programsDuration['" + i + "' = " + this.programsDuration[i], "ASXLoader", true);
	}
}

ASXLoader.getCurrentSection = function (currentTime) { // time in seconds
	var startTime = ASXLoader.arrayStartTimes[0];
	Logger.write("CurrentTime: " + currentTime, "ASXLoader", true);
	Logger.write("StartTime: " + startTime, "ASXLoader", true);
	if (currentTime <= startTime) {
		return {
			start: 0,
			duration: startTime
		};
	}
	
	
	for (var i = 0; i < ASXLoader.programsDuration.length; i++) {
		startTime += ASXLoader.programsDuration[i];
		Logger.write("for i == '" + i + "', StartTime = " + startTime, "ASXLoader", true);
		if (startTime >= currentTime) {
			return {
				start: startTime - ASXLoader.programsDuration[i],
				duration: ASXLoader.programsDuration[i]
			};
		}
	}
}