/**
 * Cellstream implemented using OOPs.
 */	

_CellstreamInstances = new Array();

 function CellStream(csOrdinates, container, data, itemsPerPage){
 					
	    this.activeLeftCoor = csOrdinates.active.left;
		this.activeTopCoor = csOrdinates.active.top;
		this.activeHeight = csOrdinates.active.height;
		this.activeWidth = csOrdinates.active.width;
		this.normalLeftCoor = csOrdinates.normal.left;
		this.normalTopCoor = csOrdinates.normal.top;
		this.normalHeight = csOrdinates.normal.height;
		this.normalWidth = csOrdinates.normal.width;		
		this.container = container;
		this.itemsPerPage = itemsPerPage;
		
		this.id = $(container).attr("id");
		this.data = data;	
		this.itemsPerPage = itemsPerPage;
		this.csPageNumber = 0;
		this.csFeedItems;
		this.csPageCount = 0;
		this.csCurrentPageElement;
		_CellstreamInstances[this.id] = this;
 }
 

CellStream.prototype.showCSNextPage = function(){
	if (this.csPageNumber < this.csPageCount) {
        this.csPageNumber++;
        this._showCellstreamPage();
        if(this.csPageNumber > 1) {
        	$('#csPrevious').removeClass('csPreviousDisabled');
        	$('#csPrevious').addClass('csPrevious');
        }
    }
    if (this.csPageNumber >= this.csPageCount) {
        $('#csNext').removeClass('csNext');
        $('#csNext').addClass('csNextDisabled');
    }
}

CellStream.prototype.showCSPrevPage = function(){
	    if (this.csPageNumber > 1) {
        this.csPageNumber--;
        this._showCellstreamPage();
        $('#csNext').removeClass('csNextDisabled');
        $('#csNext').addClass('csNext');
    }
    if (this.csPageNumber <= 1) {
        $('#csPrevious').removeClass('csPrevious');
        $('#csPrevious').addClass('csPreviousDisabled');
    }	
}

CellStream.prototype.csItem = function(){	
    this.csFeedItems = new Array();
    var cellstreamobj = this;
    feedDom = parseFeed(this.data);  
    jQuery('item', feedDom).each(function(){ 
		var item = new Object();
        item.title = jQuery(this).find('title').eq(0).text();
        item.link = jQuery(this).find('link').eq(0).text();
        item.description = jQuery(this).find('description').eq(0).text();
        item.updated = jQuery(this).find('pubDate').eq(0).text();
        item.id = jQuery(this).find('guid').eq(0).text();
        item.author = jQuery(this).find('author').eq(0).text();
        item.url = jQuery(this).find('enclosure').eq(0).attr('url');
        cellstreamobj.csFeedItems.push(item);
    });
	
    this.csPageCount = Math.ceil(this.csFeedItems.length / this.itemsPerPage);
    
    id = this.container.attr("id");
    /* Empty the container div */
    this.container.empty();
    
    /* Create Wrapper and Slider */
    cellStreamWrapper = document.createElement('div');
    $(cellStreamWrapper).attr("id", "cellStreamWrapper");
    cellStreamElement = document.createElement('div');
    $(cellStreamElement).attr("id", "cellStreamSlider");
    this.csCurrentPageElement = document.createElement('div');
    $(this.csCurrentPageElement).attr("id", "csPage0");
    $(this.csCurrentPageElement).attr("class", "csPage");
    $(cellStreamElement).append(this.csCurrentPageElement)
    $(cellStreamWrapper).append(cellStreamElement);
    this.container.append(cellStreamWrapper);	
    buttonWrap = document.createElement('div');
    $(buttonWrap).attr("id", "csButtonWrap");
    $(buttonWrap).append('<a onClick=_CellstreamInstances["' + this.id + '"].showCSPrevPage() id="csPrevious" class="csPreviousDisabled"><span></span></a>');
    $(buttonWrap).append('<a onClick=_CellstreamInstances["' + this.id + '"].showCSNextPage() id="csNext" class="csNext"><span></span></a>');
    $(buttonWrap).append('<span class="clear"/>');
    this.container.parent(".body").siblings(".foot").append(buttonWrap);
    this.showCSNextPage();	  
} 


CellStream.prototype._showCellstreamPage = function(){
	var start = this.itemsPerPage * (this.csPageNumber - 1);
    var end = this.itemsPerPage * this.csPageNumber;
    $(this.csCurrentPageElement).empty();
  	
    for (var d = start; d < this.csFeedItems.length && d < end; d++) {
        var e = '<li class="article">';
        var f = this.csFeedItems[d];
        author = f.author;
        date = f.updated;
        text = f.title;
        description = f.description;
        imageURL = f.url;
        link = f.link;
        
	if(link.match(/.*\/\/.*\/video\/.*/)) {
		type = "video";
	} else {
		type = "image";
        }
        
        /* Generate the cell element using the data and add to Cellstream Slider */
        nodeHtml = this.generateCellStreamCell(type, imageURL, text, author, date, link, d % this.itemsPerPage);
        $(this.csCurrentPageElement).append(nodeHtml);
    }  
    $(this.csCurrentPageElement).fadeIn();
    this.registerHover();
}

CellStream.prototype.generateCellStreamCell = function(type, imageURL, text, author, date, link, position){
	var cellElement = document.createElement('div');
    var contentElement = document.createElement('div');
    $(contentElement).attr("class", "csContent");
	/* Add Video Play button in case of video files */
	if (type == "video"){
		$(contentElement).append('<div id="csPlay' + position + '" class="csVideoPlayButton">' + '<a class="csPlayLink" href="' + link + '">' + '</a>' + '</div>');
	}
    /* Add the image if available */
    if (imageURL != "") {
        $(contentElement).append('<div class="' + type + '"><a href="' + link + '"><img src="' + imageURL + '"/></a></div>');
        $(contentElement).addClass('imageVideo');
    }
    
    /* Handle Text only case */
    if (imageURL == "") {
        $(contentElement).append('<div class="fullText">' + text + '</div>');
    }
    else {
        $(contentElement).append('<div class="text">' + text + '</div>');
    }
        
    /* Create the Wrapper */
    var wrapperElement = document.createElement('div');
    $(wrapperElement).attr("class", "csWrapper");
    $(wrapperElement).append('<div class="timestamp">' + date.fixCellstreamDate() + '</div>');
    $(wrapperElement).append('<div class="user">' + author + '</div>');
    $(wrapperElement).append('<div class="clear"></div>');
    
    /* Adding all of them to the cell element */
    $(cellElement).attr("id", "csCell" + position);
    $(cellElement).attr("class", "csCell");
    $(cellElement).addClass("csCell" + position);
    $(cellElement).append(contentElement);
    $(cellElement).append(wrapperElement);    
    return cellElement;
}


 
//Normal to Active state on mouse hover

CellStream.prototype.registerHover = function(){
		var registerObj = this;
	 $('#cellStreamSlider .csCell').hover(function(){ //mouseover
	 
        if (!$('#cellStreamSlider .csCell').hasClass('active')) {
            
            className = $(this).attr("class");
            index = className.substring(13);
			
            if($('#csPlay' + index)) {
            	$('#csPlay' + index).hide();
            }
			
            $(this).animate({
                width: registerObj.activeWidth + "px",
                height: registerObj.activeHeight + "px",
                top: registerObj.activeTopCoor[index] + "px",
                left: registerObj.activeLeftCoor[index] + "px"
            }, 200, 'swing');
			
            
            $(this).addClass('active');
            if($('#csPlay' + index)) {
            	$('#csPlay' + index).fadeIn();
            }
        }
    }, function(){ //mouseout
        $(this).stop();
		   	className = $(this).attr("class");
		   	index = className.substring(13);
			
		   	$('#csPlay' + index).hide();
		        
		        $(this).removeClass('active');
		        registerObj.resetActiveToNormal($(this));
		        
		        $('#csPlay' + index).fadeIn();
    })
}

//Reset from Active to Normal state on mouse out

CellStream.prototype.resetActiveToNormal = function(cell){
	    className = cell.attr("class");
	    index = className.substring(13);
	
	    cell.css({
	        width: this.normalWidth + 'px',
	        height: this.normalHeight + 'px',
	        top: this.normalTopCoor[index] + 'px',
	        left: this.normalLeftCoor[index] + 'px'
	    })
		
}

CellStream.prototype.parseFeed = function(xml){
	  if( window.ActiveXObject && window.GetObject ) {
        var dom = new ActiveXObject( 'Microsoft.XMLDOM' );
        dom.async="false";
        dom.loadXML( xml );
        return dom;
	    }
	    if( window.DOMParser ) {
	        return new DOMParser().parseFromString( xml, 'text/xml' );
	    }	       
	    throw new Error( 'No XML parser available' );
}


 /* Convert the timestamp to text format */
String.prototype.fixCellstreamDate = function(){
    var dateArray = jQuery.trim(this).split(" ");
    var dateString;    
    var remoteOffset = 0;    
    if (parseInt(dateArray[1], 10) > 0) {
        dateString = ""+dateArray[2] + " " + dateArray[1] + ", " + dateArray[3] + " " + dateArray[4];
        
        try {
	  remoteOffset = parseInt(dateArray[5], 10)/100;
	} catch(err) {
	  //ignore
  	}       
    }
    else {
        dateString = dateArray[1] + " " + dateArray[2] + ", " + dateArray[5] + " " + dateArray[3];
    }    
    
	var mobileTime = Date.parse(dateString);	
	var mobileDateObj = new Date(mobileTime);	
	var currDate = new Date();
	
	var offset = parseInt(currDate.getTime() - mobileTime) / 1000;
	offset = offset + (currDate.getTimezoneOffset() + remoteOffset * 60) * 60;
    
    /*display full timestamp if posted Date is in the future or more than 10 days ago*/
    if (offset < 0 || offset > 10 * 24 * 60 * 60) {
        return (1 + mobileDateObj.getMonth()) + '/' + mobileDateObj.getDate() + '/' + (mobileDateObj.getUTCFullYear())
    }
    
    //display mins if less then an hour ago
    if (offset < 60 * 60) {
        mins = Math.round(offset / (60));
        return mins + ' min' + (mins > 1 ? 's' : '') + ' ago';
    }
    
    //display hours if less than a day ago
    if (offset < 24 * 60 * 60) {
        hrs = Math.round(offset / (60 * 60));
        return hrs + ' hr' + (hrs > 1 ? 's' : '') + ' ago';
    }

    //display days
    days = Math.round(offset / (24 * 60 * 60));
    return days + ' day' + (days > 1 ? 's' : '') + ' ago';
}

