/**
 * Rivet Software Inc.
 * ©copyright Copyright 2006-2009 Rivet Software, Inc. All rights reserved.
 **/

RS.CompanySearch = function(){
	this.CompanyRequest = null;
	this.FilingRequest = null;
	
	this.HilightColor = '#E7EFD6';
	this.Page = -1;
	this.PageSize = -1;
	this.Query = null;
	this.Request = null;
	this.ScrollStep = 10;
	this.Tree = null;
	this.Wait = false;

	this.CompanySearch_Query = document.getElementById( 'CompanySearch_Query' );
	this.CompanySearch_Results = document.getElementById( 'CompanySearch_Results' );

	//var e = new HD.Event( this.CompanySearch_Results, 'onscroll', RS.CompanySearch.OnScoll );
	//e.Attach();
}


RS.CompanySearch.prototype.GetCompaniesQuery = function(){
	this.GetCompanies( this.CompanySearch_Query.value );
}

RS.CompanySearch.prototype.GetCompanies = function( query ){
/*
    if( this.Wait ){
        return;
    }

    this.Wait = true;
*/

	if( query != this.Query ){
		this.FilingRequest = null;
		this.Page = 0;
		this.Query = query;
	}else{
		return;
	}

	var callback = {
		'failure': objectiveReference( this.RequestFailed, this ),
		'success': objectiveReference( this.BuildCompanyTree, this )
	};

	var data = {
		'Method' : 'GetCompanies',
		'Page' : this.Page,
		'PageSize' : this.PageSize,
		'Query' : query || ''
	};
	
	data = object2Query( data );
	
	var url = RS.BaseHRef +'CompanySearch.ashx'+'?dt='+( new Date() - 0 );

	YAHOO.util.Connect.abort( this.CompanyRequest, null, false );
	this.CompanyRequest = YAHOO.util.Connect.asyncRequest('POST', url, callback, data );
}

RS.CompanySearch.prototype.BuildCompanyTree = function(o){
	var response = YAHOO.lang.JSON.parse( o.responseText );

	if ( this.Page == 0) {
		this.Tree = new YAHOO.widget.TreeView( "CompanySearch_Results");
	}

	var onExpand = objectiveReference( this.NodeExpanded, this );
	this.Tree.subscribe( "expand", onExpand );

	var treeRoot = this.Tree.getRoot();
	
	var cbDynamicLoad = objectiveReference( this.GetFilingsForCompany, this );
	var cbHilight = objectiveReference( this.Hilight, this );
	
	
	// Loop through and build our company tree
	for (var i = 0; i < response.length; i++) {
		var options = {
			label: response[i]['i_company_name'],
			id: response[i]['i_cik_number'],
			ticker: response[i]['ticker'],
			filingdate: ''
		};

		var tempNode = new YAHOO.widget.TextNode(options, treeRoot, false);
		tempNode.setDynamicLoad( cbDynamicLoad );
		tempNode.onLabelClick = cbHilight;
	}

    this.Tree.draw();

//    if( response.length ){
//    	if( this.Page > 0 ){
//	    	this.ScrollDown();
//	    }

//        this.Page++;
//    }

//    this.Wait = false;
}

RS.CompanySearch.prototype.GetFilingsForCompany = function( node, onComplete ){
	var callback = {
		'failure': objectiveReference( this.RequestFailed, this ),
		'success': objectiveReference( this.BuildFilingTree, this ),
		'argument': {
			'node' : node,
			'onComplete' : onComplete
		}
	};

	var data = {
		'CIK': node.data.id,
		'Method' : 'GetCompanyFilings'
	};
	data = object2Query( data );

	var url = RS.BaseHRef +'CompanySearch.ashx'+'?dt='+( new Date() - 0 );

	YAHOO.util.Connect.abort( this.FilingRequest, null, false );
	this.FilingRequest = YAHOO.util.Connect.asyncRequest('POST', url, callback, data );
}

RS.CompanySearch.prototype.BuildFilingTree = function(o){
	var onComplete = o.argument.onComplete;
	var parentNode = o.argument.node;
	
	var filings = YAHOO.lang.JSON.parse(o.responseText);
	var boldReport = true;

	for (var i = 0; i < filings.length; i++) {
		var filing = filings[i];
		filing.i_filing_date = RS.CompanySearch.GetDate( filing.i_filing_date );
		filing.i_filing_period = RS.CompanySearch.GetDate( filing.i_filing_period );

		var label = filing['doc_name'] + " (" + filing['i_filing_period'] + ")";
		
		// Bolding the latest Annual Report
		var type = filing['doc_name'].substring(0, 6);
		if ( boldReport && type == 'Annual' ) {
			boldReport = false;
			label = '<b>' + label + '</b>';
		}

		filing.id = filing.i_accession_number;
		filing.label = label;

		var filingNode = new YAHOO.widget.TextNode( filing, parentNode, false );
		filingNode.onLabelClick = function( node ){
			CompanySearch.Hilight( node );
			RS.Filing.LoadNode( node );
		}
	}

	if( onComplete ){
		onComplete();
	}

	this.HilightTimer( parentNode );
	//this.ScrollDown();
}

RS.CompanySearch.prototype.HilightTimer = function(node){
	var hilight = objectiveReference( this.Hilight, this );
	var runOnce = function(){
		hilight( node );
	}

	setTimeout( runOnce, 200);
}

RS.CompanySearch.prototype.Hilight = function( node ){
	if (!node)
		return;

	var branches = [ 'curHighlightedComp', 'curHighlightedFiling', 'curHighlightedYear' ];	
	for (var i = 0; i < branches.length; i++) {
		var branch = document.getElementById(this[branches[i]]);
		if( branch ){
			branch.style.backgroundColor = '#FFFFFF';
		}
	}

	for (var i = 0; i < node.depth + 1; i++) {
		var el = document.getElementById( node.labelElId );
		if( el ){
			el.style.backgroundColor = this.HilightColor;
			this[ branches[ node.depth - i ] ] = el.id;
		}

		node = node.parent;
	}
}

RS.CompanySearch.prototype.NodeExpanded = function( node ){
	this.CurrentNode = node;
}

RS.CompanySearch.prototype.RequestFailed = function( conn ){
//	debugger;
}

//RS.CompanySearch.prototype.ScrollDown = function(){
//	var div = this.CompanySearch_Results;
//	var height = div.offsetHeight;
//	
//	var pageTop = div.scrollTop + height - 16;
//	var lastTop = div.scrollHeight - height;

//	var targetTop = Math.min( pageTop, lastTop );
//	if( targetTop == lastTop ){
//		//targetTop -= 32;
//	}

//	RS.CompanySearch.Scroll( div, targetTop );
//}

//RS.CompanySearch.prototype.ScrollUp = function(){
//	var div = this.CompanySearch_Results;
//	
//	if( div.scrollTop > 0 ){
//		var height = div.offsetHeight - 16;
//		var targetTop = Math.max( 0, div.scrollTop - height );
//		
//		RS.CompanySearch.Scroll( div, targetTop );
//	}
//}

//RS.CompanySearch.OnScoll = function( e ){
//	var bottom = e.Target.scrollTop + e.Target.offsetHeight + 16;
//	if( bottom >= e.Target.scrollHeight ){
//		//Get page 2+
//		CompanySearch.GetCompaniesQuery();
//	}
//}

//RS.CompanySearch.Scroll = function( node, targetTop ){
//	var diff = node.scrollTop - targetTop;
//	
//	var add = Math.abs( diff );
//	add = Math.min( CompanySearch.ScrollStep, add );
//	add = Math.max( 0, add );

//	if( diff > 0 ){
//		add *= -1;
//	}

//	node.scrollTop += add;
//	
//	if( node.scrollTop != targetTop ){
//		var cb = function(){
//			RS.CompanySearch.Scroll( node, targetTop );
//		}

//		setTimeout( cb, 50 );
//	}
//}

/*
var x = { 
	autoScroll:function( node ){
		var el = node.getEl();
		var children = node.children.length;

		var container = document.getElementById( 'companySearchOutput' );
		if( container.scrollTop == null ){
			container.scrollTop = 0;
		}

		var elY = el.offsetTop;
		if( el.clientHeight != 0 ){
			elY -= 113;
		}

		var elY_ = elY + el.scrollHeight;
		var scrollDown = elY_ - ( container.scrollTop + container.offsetHeight );

		if( scrollDown > 0 ){
			container.scrollTop += scrollDown;
		}
	},

	asyncFailure:function(o) {}
};
*/

RS.CompanySearch.GetDate = function( dateStr ){
	var dateStr = dateStr.substring( 1, dateStr.length - 1 );
	date = eval( "new "+dateStr );
	
	var yr = date.getFullYear();

	var mon = date.getMonth() + 1;
	if( mon < 10 )
		mon = '0'+mon;
	
	var day = date.getUTCDate();
	if( day < 10 )
		day = '0'+day;
	
	return yr +"-"+ mon +"-"+ day;
}

function isScalar( obj ){
	return obj == null || !isObjective(obj);
}

function object2Query(object) {
	var query = '';
	if (object) {
		for (var prop in object) {
			var value = [];
			if (tryGetSafe(object, prop, value)) {
				value = value[0];

				if (isScalar(value)) {
					query += escape(prop) + '=' + escape(value.toString()) + '&';
				} else if (isArray(value)) {
					for (var i = 0; i < value.length; i++) {
						query += escape(prop) + '[]=' + escape(value[i].toString()) + '&';
					}
				}
			}
		}
	}

	return query.substr( 0, query.length - 1 );
}

function tryGetSafe(obj, prop, val) {
	try {
		val.push(obj[prop]);
		return true;
	} catch (e) {
		return false;
	}
}