/**
* generic.js
*
* @author
* BLIM
* KKIM
* 06 - 07 - 2010
*
* @internal
* all the low level object functions for all of the sites ui code will be here.
* a singleton object that will be the js framework for the site.
*
* @todo
* planning to create a function that can create unique objects 
* that hold its own data and contain event handlers to transform the data to html equivalents.
*
*/
var generic =
{
	// data and data managing functions.
	"config":CONFIG,
	"data":DATAPOOL,
	"get":function( key ){ return this.data.get( key ); },
	"set":function( key, value ){ this.data.set( key, value ); },


	/**
	* @internal
	* 
	*
	* @param
	*
	*
	* @return
	*
	*
	*/
	"buildPhpAppData":function( )
	{
		jQuery.ajax(
		{
			"data":{ "type":"application:buildAppData" }, "type":"post", "url":generic.config.get( 'APP_SERVICE' ), "async":false, "error":generic.errorLog,
			"success":function( response ){ }
		});
	}, // end buildPhpAppData.

	/**
	* @internal
	*	calculates the pages required for the data that is pulled from DB or cache for box style view
	*
	* @param
	*	obj:mixed
	*		array - events data array
	*		integer - number of total items
	*	maxItems - maximum number of items to be displayed
	*
	* @return
	*	size:integer - number of pages needed
	*
	*/
	"calcPages":function( obj, maxItems )
	{
		var results = false;
		
		if( !empty( obj ) && is_array( obj ) && !empty( maxItems ) )
		{
			var size = obj.length;  // objs in the database
			results = Math.ceil( parseFloat( size / maxItems ) );
		}
		else if( !empty( obj ) )
		{
			var size = Number( obj );
			results = Math.ceil( parseFloat( size / maxItems ) );
		}

		return results; // returns the number pages needed for the event items
	}, // end calcPages
	
	
	/**
	* @internal
	*
	*
	* @param
	*
	*
	* @return
	*
	*
	*/
	"callProxy":function( src )
	{
		var result = false;

		$.ajax(
		{
			"data":{ "scriptfile":src }, "type":"post", "url":generic.config.get( 'APP_SERVICE' ), "async":false, "error":generic.errorLog,
			"success":function( response ){ result = generic.parseResponse( response ); }
		});

		return result;
	}, // end callProxy.


	/**
	* currently clears only the cms application data caches.
	*
	*/
	"clearCache":function( )
	{
		jQuery.ajax(
		{
			"data":{ "type":"application:clearCache" }, "type":"post", "url":generic.config.get( 'APP_SERVICE' ), "async":false, "error":generic.errorLog,
			"success":function( response ){ }
		});
	}, // end clearCache.



	/**
	* format date to get IE comliant with date. always IE the problem child.
	*
	*/
	"formatDate":function( dateStr )
	{
		return dateStr.replace( /^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i, '$1,$2$4$3' );
	},

	
	"getLocateTime":function( timeStamp ){ return new Date( timeStamp ).toLocaleString( ); },

		
	"tweetTimeFormatter":function( timeStamp )
	{
		var now = new Date( );
		var diff = parseInt( ( now.getTime( ) - Date.parse( timeStamp ) ) / 1000 );

		var tweetTimestamp = '';
		if( diff < 60 )
		{
			tweetTimestamp += diff + ' second' + (diff == 1 ? '' : 's') + ' ago';
		}

		else if( diff < 3600 )
		{
			var t = parseInt( ( diff + 30 ) / 60 );
			tweetTimestamp += t + ' minute' + ( t == 1 ? '' : 's' ) + ' ago';
		}
		
		else if( diff < 86400 )
		{
			var t = parseInt( ( diff + 1800 ) / 3600 );
			tweetTimestamp += t + ' hour' + ( t == 1 ? '' : 's' ) + ' ago';
		}
	
		else
		{
			var d = new Date( timeStamp );
			var period = 'AM';

			var hours = d.getHours( );
			if( hours > 12 )
			{
				hours -= 12;
				period = 'PM';
			}

			var mins = d.getMinutes( );
			var minutes = ( mins < 10 ? '0' : '' ) + mins;

			var monthName = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];

			tweetTimestamp += monthName[ d.getMonth( ) ] + ' ' + d.getDate( );

			if( d.getFullYear( ) < now.getFullYear( ) ){ tweetTimestamp += ', ' + d.getFullYear( ); }

			var t = parseInt( ( diff + 43200 ) / 86400 );
			tweetTimestamp += ' (' + t + ' day' + ( t == 1 ? '' : 's' ) + ' ago)';
		}

		return tweetTimestamp;
	}, // end tweetTimeFormatter.



	/**
	* @internal
	*
	*
	* @param
	* params:mixed
	*	mediaObj - a object that contain a single media object information
	*
	* @return
	* results:mixed
	*	false: error in function
	*	null: no media found
	*	string: html code that will display a image
	*	object: { "url": url of object, "alt": atl tag of obj if any, "mediatype":id of the mediatype }
	*
	*/
	"getMedia":function( params )
	{
		var results = false;

		var defaults = { "mediaObj":null };
		
		var param = checkParams( params, defaults );

		results = ( is_array( param[ 'mediaObj' ] ) && !empty( param[ 'mediaObj' ] ) ) ? param[ 'mediaObj' ] : false;
		var mediaType = ( !empty( results[ 'media_type_id' ] ) ) ? results[ 'media_type_id' ] : false;
		
		switch( mediaType )
		{
			case '1': case '2': case '6': case '7':case '8': case '9': case '11': case '12': case '16': case '17': 
			case '18': case '19': case '23': case '24':	case '25': case '26': case '27': case '28':	case '29': case '30':
			case '40': case '41': case '42': case '43': case '44': case '45': case '46': case '47': case '48': case '49':
			case '50': case '51': case '52': case '53': case '54':

				results = this.getImage( param );
				if( results ){ results = { "media":results, "media_type_id":mediaType }; }
				break;
		/*	case '3': case '4': case '5': case '10': case '13': case '14': case '15': case '20': case '55':
				results = this.getPdf( param );
				break
			case '21': case '22': case '56':
				results = this.getVideos( param );
				break; */
			default: 
				results = null; 
				break;
		}
		
		return results;
	},
	
	
	/**
	* @internal
	*	grabs the image link data from the obj data
	*
	* @param
	*	media_obj:array - data from the DB containing a media list in json format
	*
	* @return
	*	results:mixed
	*		false - error in function
	*		string - image source html
	*/
	"getImage":function( params )
	{
		var results = false;
		
		if( is_array( params[ 'mediaObj' ] ) && !empty( params[ 'mediaObj' ] ) )
		{
			var media = params[ 'mediaObj' ];

			results = ( !empty( media[ 'url' ] ) ) ? true : false;
			results = ( !empty( media[ 'alt_tag' ] ) && results ) ? true : false;

			if( results )
			{
				results = '<img src="' + media.url +'" alt="' + media.alt_tag + '" />';
			}
		} // end for.

		return results;
	},// end getImage


	/**
	* @internal
	*	grabs the ticket and info link data from the data
	*
	* @param
	*	obj:array - data from DB that contains the venue and link data
	*
	* @return
	*	url:array - array with key TICKET with ticket link, array INFO with info link
	*
	*/
	"getLink":function( params )
	{
		/*
		var results = false;
		var defaults = { "linkObj":null }
		
		var param = checkParams( params, defaults );
		
		results = ( is_array( param[ 'linkObj' ] ) && !exist( param[ 'linkObj' ] ) ) ? param[ 'linkObj' ] : false;
		
		if( results )
		{
			results = { "url":results[ 'ur' ], "target":results[ 'target_blank' ], "linkType":results[ 'link_type_id' ]
		}*/
		var data = obj[ 'link' ];
		var venue = obj[ 'venue' ];
		var url = new Array(  );

		// default links for specific venues
		var defaultLinks = 
		{ 
			561:{ "info":"http://www.staplescenter.com/", "ticket":generic.config.get( 'DEFAULT_CFC_LINK' ) + "http://www.ticketmaster.com/venue/73985" }, 
			726:{ "info":"http://congaroom.tix.com/", "ticket":"http://congaroom.tix.com/" }, 
			727:{ "info":"http://www.nokiatheatrelalive.com/", "ticket":generic.config.get( 'DEFAULT_CFC_LINK' ) + "http://www.ticketmaster.com/venue/74438" },
			728:{ "info":"http://www.clubnokia.com/", "ticket":generic.config.get( 'DEFAULT_CFC_LINK' ) + "http://www.ticketmaster.com/venue/74500" },
			729:{ "info":"http://www.grammymuseum.org/", "ticket":generic.config.get( 'DEFAULT_CFC_LINK' ) + "http://www.ticketmaster.com/venue/74504" },
			730:{ "info":"http://www.lalive.com/play/nokiaplaza", "url":"http://www.lalive.com/play/nokiaplaza" },
			747:{ "info":"http://www.lalive.com/eventsales/venues/event-deck.html", "ticket":generic.config.get( 'DEFAULT_CFC_LINK' ) + "http://www.ticketmaster.com/venue/74512" }
		}; // end default links

		// default links
		try
		{
			url[ 'INFO' ] = { "url":defaultLinks[ venue[ 0 ][ 'venue_id' ] ][ 'info' ], "target":generic.config.get( 'TARGET_BLANK' ) }; 
			url[ 'TICKET' ] = { "url":defaultLinks[ venue[ 0 ][ 'venue_id' ] ][ 'ticket' ], "target":generic.config.get( 'TARGET_BLANK' ) };
		}
		// set default links to null if no venue id or default venue information is found
		catch( err )
		{
			url[ 'INFO' ] = false; 
			url[ 'TICKET' ] = false; 
		}


		// pulls the link from the data and places in a array
		for( var x in data )
		{
			if( data.hasOwnProperty( x ) )
			{
				if( data[ x ][ 'link_type_id' ] == generic.config.get( 'INFO_LINK_TYPE_ID' ) ){ url[ 'INFO' ] = { "url":data[ x ][ 'url' ], "target":generic.config.get( 'TARGET_BLANK' ) }; } // info link
				if( data[ x ][ 'link_type_id' ] == generic.config.get( 'TICKET_LINK_TYPE_ID' ) ){ url[ 'TICKET' ] = { "url":data[ x ][ 'url' ], "target":generic.config.get( 'TARGET_BLANK' ) }; } // ticket link
				if( data[ x ][ 'link_type_id' ] == generic.config.get( 'TICKET_EXCHANGE_LINK_TYPE_ID' ) ){ url[ 'TEAMEXCHANGE' ] = { "url":data[ x ][ 'url' ], "target":generic.config.get( 'TARGET_BLANK' ) }; } // teamexchange link
			} // end if
		} // end for


		// if there is a teamexchange link, replace the ticket link for the teamexchange
		if( url[ 'TEAMEXCHANGE' ] !== undefined ){ url[ 'TICKET' ] = url[ 'TEAMEXCHANGE' ]; }
		
		// if there is no ticket link set the ticket link to the info link
		if( url[ 'TICKET' ] === undefined || url[ 'TICKET' ] === null || url[ 'TICKET' ] == '' ){ url[ 'TICKET' ] = url[ 'INFO' ]; }

		return url;	
	}, // end getLink


	/**
	* @internal
	*	changes the status id to an equivalent string that can be displayed through html
	*
	* @param
	*	status:integer - status id
	*
	* @return
	*	string - returns the status id equivalent string within the status associations list
	*
	*/
	"getStatusAssoc":function( status )
	{
		var status_assoc = { "0":"OTHER", "1":"TICKET", "2":"FREE", "3":"FREE", "4":"CANCELLED", "5":"POSTPONED", "6":"SOON", "7":"SOLD OUT", "8":"TBD", "9":"TICKET" };

		return status_assoc[ status ];
	}, // end getStatusAssoc


	/**
	* @internal
	*	grabs the venue data from the data
	*
	* @param
	*	obj:array - a
	*
	* @return
	*	url:string - returns venue title from the data
	*
	*/
	"getVenue":function( obj )
	{
		var url = 'L.A. LIVE';

		// checks to see if venue data is empty or not
		if( obj[ 'venue' ] )
		{
			var data = obj[ 'venue' ];
			url = data[ 0 ][ 'title' ];
		} // end if

		return url;	
	},// end getVenue


	/**
	* @internal
	* loads css
	*
	* @param
	* 	src:string - filepath of the module
	*
	* @return
	*
	*
	*/
	"loadCSS":function( src )
	{
		this.logActivity( 'module: http://lalive.com/' + src );
		var script = document.createElement( 'link' );
		script.type = 'text/css';
		script.rel = 'stylesheet';
		script.href = src;
		document.body.appendChild( script );
	}, // end loadCSS


	/**
	* @internal
	* load any moodules that requires a script tag
	*
	* @param
	* src:string - filepath of the module
	*
	* @return
	* None
	*
	*/
	"loadModule":function( src, callback )
	{
		var script = document.createElement( 'script' );
		script.setAttribute( 'src', src );
		document.body.appendChild( script );

		if( callback )
		{
			script.onreadystatechange = function( )
			{
				if( script.readyState == 'loaded' || script.readyState == 'complete' ){ callback( ); }
			}

			script.onload = function ( ){ callback( ); return; }			
		} // end callback.
	}, // end loadModule.


	/**
	* @internal
	* hack to fix ie7s z-index issue.
	*
	* @param
	* empty.
	*
	* @return
	* empty.
	*
	*/
	"fixzIndex":function( )
	{
		var zIndexNumber = 1000;
		$( 'div' ).each( function( )
		{
			if( $( this ).attr( 'id' ) != 'footer' )
			{
				$( this ).css( 'zIndex', zIndexNumber );
				zIndexNumber -= 10;
			}
			else{ return false; }
		});

		$( 'div.paging' ).css( 'zIndex', 1000 );
		$( 'ul.sf-menu' ).find( 'li' ).each( function( )
		{
			$( this ).css( 'zIndex', 1000 );
		} );
	}, // end fixzIndex.
	

	/**
	* @internal
	* logs activity
	*
	* @param
	* message:string - whats is being accessed
	*
	* @return
	* empty
	*
	*/
	"logActivity":function( message )
	{
		if( this.config.get( 'DEBUG' ) )
		{
			if( document.getElementById( 'right' ) === null ){  }

			else
			{
				var entry = document.createElement( 'p' );
				entry.setAttribute( 'class', 'logItem' );
				entry.innerHTML = message;
				document.getElementById( 'right' ).appendChild( entry );
			}
		}
	}, // end logModules.


	/**
	* @internal
	* log errors. 
	*
	* @param
	* message:string - error
	*
	* @return
	* empty
	*
	*/
	"logError":function( message )
	{
		if( generic.config.get( 'DEBUG' ) )
		{
			if( document.getElementById( 'resultsPanel' ) === null ){ var errMsg = 'there was an error (;_;)\n\n' + message; }
			else{ $( '#resultsPanel' ).find( 'pre' ).append( message ); }
		}
	}, // end logError.


	/**
	* @internal
	* parse the server side response and return a json object.
	*
	* @param
	* response:string - the server side response.
	*
	* @return
	* mixed:
	*	false:
	*	object:
	*
	*/
	"parseResponse":function( response )
	{
		var result = false;

		try{ result = $.parseJSON( response ); result = result.result; }
		catch( e ){ generic.logError( var_export( e, true ) ); }

		return result;
	}, // end process.


	/**
	* @internal
	* general ajax function for all service related calls to the server.
	*
	* @param
	* param, mixed
	* 	data - a json object containing the data being sent to the server.
	*	url - the path to the service file. ** check js.settings for this value **
	*
	* @return
	* result:mixed,
	*	false - function or ajax call failure.
	*	object - good result message with data.
	*
	*/	
	"serviceCall":function( param )
	{
		var result = false;
		
		$.ajax(
		{
			"data":param[ 'data' ], "type":"post", "url":param[ 'url' ], "async":false, "error":generic.errorLog,
			"success":function( response ){ result = generic.parseResponse( response ); }
		});
		
		return result;
	} // end serviceCall.
} // end generic.

