/**
* filename
* news.js
* 
* Ki-Chang Kim
* kkim@aegworldwide.com
* May 12, 2010
*
* @internal
* this file will populate the news module headlines, and news detail page content
*
*
*/

var newsMod =
{
	"data":{ },
	/**
	* @internal
	*	calculates the pages required for the data that is pulled from DB or cache for box style view
	* @param
	*	param:array
	*		obj:array - array of db data, used to help calculate total pages needed by using its length
	*
	* @return
	*	size:integer - number of pages
	*
	*/
	"calcPages":function( obj, numItems )
	{
		var size = obj.length;  //objs in the database
		var maxItems = numItems;
		
		size = Math.ceil( parseFloat(size / maxItems) );
	
		return size; //returns the number pages needed for the event items
	}, // end calcPages

	/**
	* @internal
	* this function will return data that will be used to display the news listing page
	*
	* @param
	* param:array
	*		obj:array - array of db data, used to help calculate total pages needed by using its length
	*
	* pos:integer - pos of the first item to be displayed on the news item page
	*
	* displayNum:integer - number of items to be displayed per page
	*
	* @return
	* html:string - string that holds the details of the news content in html format
	*
	*/
	"displayNewsList":function( obj, pos, displayNum )
	{
		var data = obj;
		
		/****************************************************************
		* checks to see if pos + viewnum is less than the number of items in the obj
		* if true the max number of iterations for the for loop is set to pos + displayNum
		* else max number of iterations is set the the length of obj
		*****************************************************************/
		if( ( pos + displayNum ) < data.length ) { var viewNum = pos + displayNum; }
		else { var viewNum = data.length }

		var href = '';
		var image = '';
		var title= '';
		var date = '';
		var description = '';
		
		if( $( '#homepageNews' ).length > 0 ){ var htmlWrap = newsMod.getTemplate( '../news/listTemplate.html', 'list' ); }
		else{ var htmlWrap = newsMod.getTemplate( '../news/pressTemplate.html', 'list' ); }

		var html = '';

		/****************************************************************************
		* iterating through obj displayNum of times from pos position in the obj 
		* data to get news detail id, date, link, title and wrap it with html
		****************************************************************************/
		for( var x = pos; x < viewNum; x++)
		{
			title = data[ x ][ 'title' ];
			date = data[ x ][ 'news_date' ];
			id = data[ x ][ 'id' ] + '|' + pos;
			link = 'javascript:;';
			html += this.str_replace( [ '<!--||LINK||-->', '<!--||NEWS||-->', '<!--||DATE||-->', '<!--||NEWS_ID||-->' ], [ link, title, date, id ], htmlWrap );
		} //end of for



		return html;
	},//end displayNewsList

	/**
	* @internal
	* grabs the link from the news data
	*
	* @param
	* param:array
	*		obj:array - array of db data, used to help calculate total pages needed by using its length
	*
	* @return
	* link:string - url information for the specific news
	*
	*/
	"getLink":function( obj )
	{
		var link;

		for( var x in obj )
		{
			if( obj[ x ][ 'label' ] == 'INFO' ){ link = obj[ x ][ 'url' ]; }
			else{ link = 'no link'; }
		} // end of for

		return link;
	},//end getLink

	/**
	* @internal
	* grabs the image src from the news data
	*
	* @param
	* param:array
	*		obj:array - array of db data, used to help calculate total pages needed by using its length
	*
	* @return
	* image:string - url information for the image to be displayed for the specific news
	*
	*/
	"getImage":function( obj )
	{
		var image;
		image = obj[ 0 ][ 'url' ];
		return image;
	},//end getImage


	/**
	* @internal
	*	retrieves the html file
	*
	* @param
	*	view:string - what type of display view, either 'grid' for box view or 'list' for list view
	*
	* @return
	*	results:mixed
	*		results:mixed
	*			default - false, if there is no data or ajax call fails
	*			string - contents of the file
	*
	*/
	"getTemplate":function( file, type )
	{
		var filepath = '/content/'+file;
		// returns the template html wrap according to the file
		var results = false;

		// checks if there is a template or not stored
		if( newsMod.data[ type ] === undefined || newsMod.data[ type ] === false )
		{
			$.ajax(
			{
				"data":[ ], "type":"post", "url":filepath, "async":false,
				"success":function( response ){ results = response; }
			}); // end ajax call for templates

			// sets new template
			newsMod.data[ type ] = results;
		} // end of if
		
		// retrieves stored template
		else{ results = newsMod.data[ type ]; }

		return results;
	},// end getTemplate

	/**
	* @internal
	* opens a new popup window with html code written to the new window
	*
	* @param
	* obj:array - contents of a single news item
	*
	* @return
	* none
	*
	*/
	"newsDetail":function( obj )
	{
		var html = false;

		// html template file for the news detail
		html = newsMod.getTemplate( '../news/detailsTemplate.html', 'details' );
		
		// checks if template, and obj has data
		if( html !== false && obj !== undefined && obj !== null && obj !== false )
		{
			// creates a new window
			var popUp = window.open( '','newsdetail_' + obj[ 'id' ] , 'height=400,width=560,dependent=yes,resizable=no,scrollbars=yes,location=no,toolbar=no' );

			// clears window if a window is already open
			popUp.document.write( '' );
			// preps data to be written
			html = newsMod.str_replace(
				[ '<!--||NEWS_TITLE||-->', '<!--||NEWS_DATE||-->', '<!--||NEWS_DETAIL||-->' ],
				[ obj[ 'title' ], obj[ 'news_date' ], obj[ 'body' ] ],
				html);

			// writes data to the window
			popUp.document.write( html );
		} // end if

		// this is where we should log errors
		else
		{
			var error = new Array( );
			if( html !== false ){ error.push( 'HTML template file is missing' ); }
			if( obj !== undefined && obj !== null && obj !== false ){ error.push( 'Error in obj: ' + obj ); }
		} // end else
	},//end getImage

	/**
	* @internal
	*	controller that moves the pagination page icons depending on the selected page
	*
	* @param
	*	pagePos:integer - the page number that the user wishes to go to
	*
	*	maxPages:integer - maximum number of pages needed to list all the data
	*
	* @return
	* 	html:string - string that holds the pagination details for display
	*
	*/
	"pagination":function( pagePos, maxPages )
	{
		var minPage = parseInt(pagePos) - 2;  //sets start index of pagination for total of 5 page selectors
		var maxPage = parseInt(pagePos) + 2;  //sets end index of pagination for total of 5 page selectors

		var totalPages = maxPages;

		var content = '';
		var html = '<div class="results" style="display:block;">\
					<div id="pagination" style="padding-bottom:35px;float:right;width:100%">\
					<div style="padding-left:18px;float:left;font-size:11px;color:grey;">Displaying Page ' + ( parseInt( pagePos ) + 1 ) + ' of ' + totalPages + '</div>'


		//turns off the next button when user is on last page by making it a div instead of a anchor so that JS does not pick it up
		if( pagePos == totalPages - 1 )
		{
			html +='<div style="float:right;" page="next" id="pageNext">NEXT</div>\
                    <!-- Start Dynamic Paging -->\
					<!--<a class="pageNumber" page="+5" style="float:right;">...</a>-->';
		} // end of if

		else
		{
             html +='<a style="float:right;cursor:pointer;" page="next" id="pageNext">NEXT</a>\
                    <!-- Start Dynamic Paging -->\
					<!--<a class="pageNumber" page="+5" style="float:right;">...</a>-->';
		} // end of else


		//turns off the prev button when user is on first page by making it a div instead of a anchor so that JS does not pick it up
		if( pagePos == 0 )
		{
			var htmlEnd = '<!-- End Dynamic Paging -->\
					<!--<a class="pageNumber" page="-5" style="float:right;">...</a>-->\
					<div style="float:right;" page="prev" id="pagePrev">PREV</div>\
	                </div>\
					</div>';
		} // end of if

		else
		{
			var htmlEnd = '<!-- End Dynamic Paging -->\
					<!--<a class="pageNumber" page="-5" style="float:right;">...</a>-->\
					<a style="float:right;cursor:pointer;" page="prev" id="pagePrev">PREV</a>\
	                </div>\
					</div>';
		} // end of else


		//checks to see if the selected page index is lower than 3 so that it won't show 0 or -1 page selector
		if( parseInt(minPage) < 2 )
		{
			minPage = 0;
			if( parseInt( totalPages ) > 4 )
				maxPage = 4;
			else
				maxPage = totalPages;
		} // end of if


		//checks to see if the selected page index is higher than the number data objects so that it won't show a page selector greater than the data has to offer
		if( maxPage >= parseInt( totalPages ) )
		{
			minPage = parseInt( totalPages ) - 5;
			if( minPage < 0 )
				minPage = 0;
			maxPage = parseInt( totalPages ) - 1;	
		}// end of if


		//creates html for page selector with the page number index
		for(var x = minPage; x <= maxPage; x++)
		{
			if( x == pagePos){ content = '<div class="pageNumberCurr" page="' + x +'" style="float:right;">' + (x + 1) + '</div>' + content; }
			else{ content = '<a class="pageNumber" page="' + x +'" style="float:right;cursor:pointer;">' + (x + 1) + '</a>' + content; }
		} // end of for

		html += content + htmlEnd;

		return html;
	},//end of pagination

	/**
	* @internal
	*	controller that changes the view port to the selected page
	*
	* @param
	*	param:array
	*		pageData:string - array of pages that holds a list of data item list in each index page
	*		list:string - data from the DB containing the data list items
	*
	*	page:integer - page that needs to be display in conjunction with pageData index, or adds new page data to the pageData
	*
	*	maxPages:integer - max pages needed for all the items in list
	*
	* @return
	*	
	*/
	"pageController":function( pageData, list, page, maxPages)
	{


		/***************************************************************************************
		* checks to see if page is null, less than 0, leess than maxPages
		* if it is null set the default page location to the first page
		* if less than set the page location to the first page
		* if less than maxPages set the page location to the page requested
		* else set the page location to the last page of the list
		***************************************************************************************/
		if( page == null ){ var pagePos = 0; }
		else if( page < 0 ){ var pagePos = 0; }
		else if( page < maxPages){ var pagePos = page; }
		else{ var pagePos = parseInt( maxPages ) - 1; }

		if( pageData == null ){ pageData = new Array(); }

		if( pageData[ pagePos ] != null )
		{
			$( "#news" ).html( pageData[ pagePos ] );
			$( "#paging" ).html( newsMod.pagination( pagePos, maxPages ) );
			$( 'a[page]' ).click( function( )
			{
				var pageMove = $( this ).attr( 'page' );
				if( pageMove == 'prev' ){ pageMove = parseInt( pagePos ) - 1; }
				else if( pageMove == 'next' ){ pageMove = parseInt( pagePos ) + 1; }
				newsMod.pageController( pageData, list, pageMove, maxPages );
			});
		} // end of if

		else
		{
			pageData[ pagePos ] = newsMod.displayNewsList( list, pagePos * 13 , 13 );
			$( "#loading" ).fadeOut( 'slow', function( ){ $( "#news" ).fadeIn( 'slow' ); } );
			$( "#news" ).html( pageData[ pagePos ] );
			$( "#paging" ).html( newsMod.pagination( pagePos, maxPages ) );
			$( 'a[page]' ).click( function( )
			{
				var pageMove = $( this ).attr( 'page' );
				if( pageMove == 'prev' ){ pageMove = parseInt( pagePos ) - 1; }
				else if( pageMove == 'next' ){ pageMove = parseInt( pagePos ) + 1; }
				newsMod.pageController( pageData, list, pageMove, maxPages );
			});
		} //end of else
		

		/************************************************
		* Homepage specific code, to display the list of
		* news if the id homepageNews is present
		*************************************************/		
		if( $( "#newsList" ).length !== 0 )
		{
			var homepageList = newsMod.displayNewsList( list, 0, 20 );
			$( "#newsList" ).html( homepageList );
			$( "#loading" ).fadeOut( 'slow', function( ){ $( "#homepageNews" ).fadeIn( 'slow' ); } );
		} // end of if


		// creates a pop-up window for details page
		$( ".newsLink" ).click( function( )
		{ 
			var item = $( this ).attr( 'id' );

			item = item.split( "|" );
		
			// finds the item that needs to be diplayed from the list of news items
			for( var x = item[ 1 ]; x < list.length; x++ )
			{
				if( list[ x ][ 'id' ] == item[ 0 ] )
				{
					var newsItem = list[ x ];
					break;
				}
			} // end for

			// creates the pop-up for news detail
			newsMod.newsDetail( newsItem );

		} ); // end pop-up jquery
	}, // end pageController

	/**
	* @internal
	*	str_replace for js
	*/
	"str_replace":function( search, replace, subject, count )
	{
		var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0, f = [ ].concat( search ), r = [ ].concat( replace ), s = subject, 
			ra = r instanceof Array, sa = s instanceof Array; s = [ ].concat( s );

		if( count ){ this.window[count] = 0; }
		for( i = 0, sl = s.length; i < sl; i++ ){ if( s[ i ] === '' ){ continue; }
		for( j = 0, fl = f.length; j < fl; j++ )
		{
			temp = s[ i ]+'';
			repl = ra ? ( r[ j ] !== undefined ? r[ j ] : '' ) : r[ 0 ];
			s[ i ] = ( temp ).split( f[ j ] ).join( repl );
			if( count && s[ i ] !== temp ){ this.window[ count ] += ( temp.length - s[ i ].length ) / f[ j ].length; } }
		}

		return sa ? s : s[ 0 ];
	}
};//end newsMod


$( function () {

	var result = false;

	// gets the news data from DB
	$.ajax(
	{
		"data":{ "setting":location.host },
		"type":"post", 
		"url":"../ajax/news.service.php", 
		"async":false, 
		"success":function( response ){ result = response; }
	}); // end DB call

	var list = $.parseJSON( result );

	if( result != null )
	{
		// display the list of news items starting from the first 13 most recent items
		var maxPages = newsMod.calcPages( list, 13 );
		var storedPages = new Array();
		newsMod.pageController( storedPages, list, 0, maxPages );
	} //end of if

	// for homepage scrolling using scrollbarpaper plugin
	if( $( '#homepageNews' ).length > 0 ){ $( "#homepageNews" ).scrollbarPaper(); }
}); // end of DOM ready
