/*
* :TODO: 
* commenting
* global config section
*
*/

Function.prototype.inheritsFrom = function( oParent ){ 
	this.prototype = new oParent;
	this.prototype.constructor = this;
	this.prototype.parent = oParent.prototype;	
	
	return this;
} 

Quotr = function() { 		  
  that = this; 
};

Quotr.prototype = {
  init: function( scriptdir ) {
    this.showQuoteMessage( "<p>Loading ...</p>" );

    $.ajax({
      type: "GET",
      url: "/stock/quote",
      success: this.displayQuote,
      timeout: 15000,
      error: this.reportError
    });
  },    
  displayQuote: function ( o ) {	

  },	
  addPair: function ( o, a, v ) {
    that.addAttr( o, a );
    that.addValue( o, v );
  },  	
  addAttr: function ( o, a ) {
    $("#quote_fields").append( "<p>" + a + ": </p>");
  },  	
  addValue: function ( o, v ) {
    $("#quote_vals").append( "<p>" + $( v, o ).text() + "</p>");
  },  	
  showQuoteMessage: function ( msg ) {
    $( "#quote_message" ).html( msg );
    $( "#quote_message" ).css( { display:"block" } );
  },  	
  hideQuoteMessage: function () {
    $( "#quote_message" ).css( { display:"none"	} );
    $( "#quote_message" ).empty();
  },  	
  youFailIt: function () {
    showQuoteMessage( "<p>Failed to retrieve quote</p>")
  },
  months : [ "Jan", "Feb", "Mar" , "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]
}

HomeQuotr = function() {};
HomeQuotr.inheritsFrom( Quotr ) 
HomeQuotr.prototype.displayQuote = function(o) {
  that.hideQuoteMessage();		
  
  if ( $("status",o).text() == "pass" ) {   
    that.addPair( o, "Last", "last" );
    that.addPair( o, "High", "high" );
    that.addPair( o, "Low", "low" );
    that.addPair( o, "Change", "change" );
    
    var date = "";
    //if the market is closed then tradetime contains the date of the last close
    //else if the market is open it contains the time of the last trade
    if ( $( "tradetime", o ).attr( 'market') == "closed" ) {
      date =  $( "tradetime", o ).text();
    }
    else {
      var d = new Date ( $( "today", o ).text() );    		
     date = d.getDate() + " " + that.months[ d.getMonth() ] + " " + d.getFullYear();
    }
    $( "#quote_fields" ).append( "<p>Date:</p>" );
    $( "#quote_vals" ).append( "<p>" + date + "</p>");
  } 
  else {
    that.showQuoteMessage( "<p>Failed to retrieve quote</p>" );
  }
}
/*
* :KLUDGE: did this in order to call news script upon completion
*/
HomeQuotr.prototype.init = function(scriptdir ) {
	that.showQuoteMessage( "<p>Loading ...</p>" );

	//url: scriptdir + "quotr.php?s=kalg.ob",
	$.ajax({
		type: "GET",
    url: "/stock/quote",
    success: this.displayQuote,
		timeout: 15000,
		complete: this.loadNews,
		error: this.reportError
	});
}    
HomeQuotr.prototype.loadNews = function( ) {
    //return;
    var myNewsTicker = new NewsTicker();
		myNewsTicker.init();
},
HomeQuotr.prototype.reportError = function( ) {
   that.showQuoteMessage( "<p>Failed to retrieve quote</p>" );
}


InvestorsQuotr = function() {};
InvestorsQuotr.inheritsFrom( Quotr ) 
InvestorsQuotr.prototype.displayQuote = function(o) {
  that.hideQuoteMessage();		
  
  if ( $("status",o).text() == "pass" ) {   
    that.addPair( o, "Last", "last" );
    that.addPair( o, "High", "high" );
    that.addPair( o, "Low", "low" );
    that.addPair( o, "Change", "change" );
    that.addPair( o, "Volume", "volume" );
    
    var date = "";
    //if the market is closed then tradetime contains the date of the last close
    //else if the market is open it contains the time of the last trade
    if ( $( "tradetime", o ).attr( 'market') == "closed" ) {
      date =  $( "tradetime", o ).text();
      
      $( "#quote_fields" ).append( "<p>Date:</p>" );
      $( "#quote_vals" ).append( "<p>" + date + "</p>");
    }
    else {
      var d = new Date ( $( "today", o ).text() );    		
      date = d.getDate() + " " + that.months[ d.getMonth() ] + " " + d.getFullYear();
    
      $( "#quote_fields" ).append( "<p>Date:</p>" );
      $( "#quote_vals" ).append( "<p>" + date + "</p>");
    
      that.addPair( o, "Time", "tradetime" );
    }
  } 
  else {
    that.showQuoteMessage( "<p>Failed to retrieve quote</p>" );
  }
}


/* ----------------------------------------------------------------------------------------------*/

NewsTicker = function() { 		  
  that = this; 
};

NewsTicker.prototype = {
  init: function() {
    $.ajax({
      type: "GET",
      url: "/news/latest-news",
      success: this.gotNews,
      timeout: 5000,
      error: this.youFailIt
    });
  },    
  gotNews: function ( o ) {	
    var objNews = [];

    $("article", o ).each(function( i ) {
      var news_link = "/news/article/" + $("alias", this ).text();
    
    
      objNews[i] = { item: $("title", this ).text(), link: news_link, date: $("date", this ).text() };
    });
    
    $("div.ticker p").ticker( objNews, {blank: false} );
  },
  youFailIt: function () {
  	$("div.ticker p").html( "Failed to retrieve latest news" );
  }
}




//from jquery.ticker.js
/* **************************************************
//
// Ticker
// Fade In / Fade Out Text or Images
//
// Created : 4th November 2006
//
// Copyright Simon Corless sico.co.uk
// Use and alter as you please, if you make any good changes let me know!
//
// Influenced by http://www.learningjquery.com/2006/10/scroll-up-headline-reader
// and other jQuery documentation and plugins
//
//
************************************************** */

// Extend jquery into our function 
jQuery.fn.ticker = function(items, options) {
    var self = this;
    var i = 0;
    var interval;

    var settings = {
        timeout: 5000,
        blank: true
    };

    // Overwrite the settings with the options sent to the script
    if(options) {
        $.extend(settings, options);
    };

    // Call the next item in the array of items
    nextItem = function () {
        self.fadeOut("slow",function() {

            if (items[i]['link']) {								
							self.html( items[i]['date'] + " <a href=\"" + items[i]['link'] + "\">" + items[i]['item'] + "</a>");
            } else {
                self.html(items[i]['item']);
            }
            self.fadeIn("slow");
            i = (i + 1) % items.length; // Modulus : The value will always equal i+1 until i == news.length when it will = 0
        });
    }

    function pause() {
        clearInterval(interval);
    }

    function resume() {
        interval = setInterval(nextItem,settings['timeout']);
    }

    // Carry out the actions on the element
    return this.each(function() {
        // Call the next item to initialise the rotator
        if (settings['blank']) {
            self.html("");
            nextItem();
        }
        // Set the interval for the nextItem function
        resume();

        self.hover(pause,resume);
    });
};