﻿/*
======== table of content. =================================

Name: jLPO.js (Simple LPO Library for jQuery)
Versiton: 1.0.1
Description: When referrer hits keywords(and etc),
             replace contents with a file data.
Update: 2010/10/06-
Author: Japan Electronic Industrial Arts Co.Ltd.
        http://jeia.co.jp/
Using: Using jQuery on MIT lisence
Lisence: LGPL lisence

Usage:
------------------------------------------------------------
<script type="text/javascript"
 src="http://www.google.com/uds/api?file=uds.js&amp;v=1.0"></script><!-- when using 'area' option -->

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="lpo.js"></script>
<script type="text/javascript">
	jLPO.add( _selector, _file, _opts );
</script>
------------------------------------------------------------
+ _selector
... jQuery selector string ( hit only first )
ex) '#example'

+ _file
... text file path
ex) './example.txt'

+ _opts
... access condition object
ex) { visited: true, keyword:'example' }

	+ visited	...	boolean (true/false)
	+ last		...	number (Minutes ago)
	+ keyword	...	string
	+ referrer	...	string (URL, Wildcard(*) is usable)
	+ param		... 'name=value'
	+ startTime	...	'00:00'
	+ endTime	...	'00:00'
	+ startDate	...	'2010/00/00 00:00'
	+ endDate	...	'2010/00/00 00:00'
	+ weekday	... string (Sun,Mon,Tue,Wed,Thu,Fri,Sat)
	+ area		...	string (City name in the local language)


============================================================
*/

if ( typeof jLPO == 'undefined' ) {
	var jLPO = {};
}

(function($) {
	
	jLPO.list = {};
	jLPO.now = new Date();
	jLPO.last = null;
	jLPO.cookieKey = 'jLPO';
	jLPO.cookieMaxDate = 365;
	
	$(document).ready( function() {
		jLPO.init();
	});
	
	/**
	 * add
	 */
	jLPO.add = function( _selector, _file, _opts ) {
		if ( typeof( this.list[ _selector ] ) == 'undefined' ) {
			this.list[ _selector ] = new this.LPOClass( _selector );
		}
		this.list[ _selector ].add( new this.checkClass( _file, _opts ) );
	};
	
	/**
	 * init
	 */
	jLPO.init = function() {
		this.last = this.cookie( this.cookieKey );
		this.cookie( this.cookieKey, this.now.getTime() );
		
		var i;
		
		for ( i in this.list ) {
			this.list[i].reset();
		}
		
		for ( i in this.list ) {
			this.list[i].check();
		}
	};
	
	/**
	 * get/set Cookie value
	 */
	jLPO.cookie = function( _key, _val ) {
		var val = null;
		var cookies = (document.cookie != '' ) ? document.cookie.split( ';' ) : [];
		var date = new Date();
		date.setTime( date.getTime() + this.cookieMaxDate * 1000 * 60 * 60 * 24 );
		
		var i;
		for ( i = 0; i < cookies.length ; i ++ ) {
			var index = cookies[i].indexOf( '=' );
			var key = cookies[i].substring(0, index);
			key = key.replace( new RegExp( '^\\s+', 'i' ), '' );
			
			if ( key == _key ) {
				val = ( typeof _val != 'undefined' ) ? _val : decodeURIComponent( cookies[i].substring(index + 1) );
			}
		}
		
		if ( typeof _val != 'undefined' ) {
			document.cookie = _key + '=' + _val + ";expires=" + date.toUTCString();
		}
		
		return val;
	};
	
	/**
	 * get Referrer Keyword
	 */
	jLPO.getRefKeyword = function() {
		var keyword = '';
		
		if ( document.referrer ) {
			var ref = document.referrer;
			
			// Google
			if ( ref.match( new RegExp( '^http:\/\/(www)?\.?google.*', 'i' ) ) ) {
				if ( ref.match( new RegExp( 'q=' ) ) ) {
					keyword = ref.replace( new RegExp( '^.*[&?]q=([^&]+)&?.*$', 'i' ), '$1' );
				}
			}
			// Yahoo
			else if ( ref.match( new RegExp( '^http:\/\/search\.yahoo.*', 'i' ) ) ) {
				if ( ref.match( new RegExp( 'p=' ) ) ) {
					keyword = ref.replace( new RegExp( '^.*[&?]p=([^&]+)&?.*$', 'i' ), '$1');
				}
			}
			// bing
			else if ( ref.match( new RegExp( '^http:\/\/www\.bing\.com\/search.*', 'i' ) ) ) {
				if ( ref.match( new RegExp( 'q=' ) ) ) {
					keyword = ref.replace( new RegExp( '^.*[&?]q=([^&]+)&?.*$', 'i' ), '$1');
				}
			}
			
			keyword = decodeURIComponent( keyword );
		}
		
		return keyword;
	};
	
	/*---------------------------------------------------
	 * LPO class
	 */
	jLPO.LPOClass = function( _selector ) {
		this.selector = _selector;
		this.temp = '';
		this.file = '';
		this.checkList = [];
		
		return this;
	};
	
	/* add */
	jLPO.LPOClass.prototype.add = function( _checkObj ) {
		this.checkList.push( _checkObj );
	};
	
	/* reset */
	jLPO.LPOClass.prototype.reset = function() {
		var $target = $( this.selector ).eq(0);
		this.temp = $target.html();
		$target.html( '' );
	};
	
	/* check */
	jLPO.LPOClass.prototype.check = function() {
		var i, file;
		for ( i = 0; i < this.checkList.length; i ++ ) {
			file = this.checkList[i].getFile();
			
			if ( file != '' ) {
				this.file = file;
			}
		}
		
		var $target = $( this.selector ).eq(0);
		
		if ( this.file != '' ) {
			$.get( this.file, {}, function(_d) {
				$target.html( _d );
			});
		}
		else {
			$target.html( this.temp );
		}
	};
	
	/*---------------------------------------------------
	 * check class
	 */
	jLPO.checkClass = function( _file, _opts ) {
		this.file = _file;
		this.visited   = ( typeof( _opts[ 'visited'   ] ) != 'undefined' ) ? _opts[ 'visited'   ] : null;
		this.last      = ( typeof( _opts[ 'last'      ] ) != 'undefined' ) ? _opts[ 'last'      ] : null;
		this.keyword   = ( typeof( _opts[ 'keyword'   ] ) != 'undefined' ) ? _opts[ 'keyword'   ] : null;
		this.referrer  = ( typeof( _opts[ 'referrer'  ] ) != 'undefined' ) ? _opts[ 'referrer'  ] : null;
		this.param     = ( typeof( _opts[ 'param'     ] ) != 'undefined' ) ? _opts[ 'param'     ] : null;
		this.startTime = ( typeof( _opts[ 'startTime' ] ) != 'undefined' ) ? _opts[ 'startTime' ] : null;
		this.endTime   = ( typeof( _opts[ 'endTime'   ] ) != 'undefined' ) ? _opts[ 'endTime'   ] : null;
		this.startDate = ( typeof( _opts[ 'startDate' ] ) != 'undefined' ) ? _opts[ 'startDate' ] : null;
		this.endDate   = ( typeof( _opts[ 'endDate'   ] ) != 'undefined' ) ? _opts[ 'endDate'   ] : null;
		this.weekday   = ( typeof( _opts[ 'weekday'   ] ) != 'undefined' ) ? _opts[ 'weekday'   ] : null;
		this.area      = ( typeof( _opts[ 'area'      ] ) != 'undefined' ) ? _opts[ 'area'      ] : null;
		
		return this;
	};
	
	/* check hit & return file path */
	jLPO.checkClass.prototype.getFile = function() {
		if ( this.checkVisited( this.visited )
		&& this.checkLast( this.last )
		&& this.checkKeyword( this.keyword )
		&& this.checkReferrer( this.referrer )
		&& this.checkParam( this.param )
		&& this.checkTime( 'start', this.startTime )
		&& this.checkTime( 'end', this.endTime )
		&& this.checkDate( 'start', this.startDate )
		&& this.checkDate( 'end', this.endDate )
		&& this.checkWeekday( this.weekday )
		&& this.checkArea( this.area ) ) {
			return this.file;
		}
		else {
			return '';
		}
	};
	
	/* check is hit visited */
	jLPO.checkClass.prototype.checkVisited = function( _visited ) {
		if ( _visited != null ) {
			if ( ( _visited && jLPO.last == null )
			||	( ! _visited && jLPO.last != null ) ) {
				return false;
			}
		}
		
		return true;
	};
	
	/* check is hit last access */
	jLPO.checkClass.prototype.checkLast = function( _last ) {
		var last1 = new Date();
		var last2 = new Date();
		
		if ( _last != null ) {
			if ( jLPO.last != null ) {
				last1.setTime( parseInt( jLPO.last, 10 ) );
				last2.setTime( jLPO.now.getTime() - _last * 1000 * 60 );
				
				if ( last1.getTime() >= last2.getTime() ) {
					return false;
				}
			}
			else {
				return false;
			}
		}
		
		return true;
	};
	
	/* check is hit keyword */
	jLPO.checkClass.prototype.checkKeyword = function( _keyword ) {
		if ( _keyword != null ) {
			var keyword = jLPO.getRefKeyword();
			
			if ( keyword != '' ) {
				var keywords1 = _keyword.split( ',' );
				var i1, len1 = keywords1.length;
				var hit1 = false;
				
				for ( i1 = 0; i1 < len1; i1 ++ ) {
					keywords1[i1] = keywords1[i1].replace( new RegExp( '^\\s+', 'i' ), '' );
					
					var keywords2 = keywords1[i1].split( ' ' );
					var i2, len2 = keywords2.length;
					var hit2 = true;
					
					for ( i2 = 0; i2 < len2; i2 ++ ) {
						if ( keywords2[i2].length > 0
						&&	keyword.indexOf( keywords2[i2], 0 ) < 0 ) {
							hit2 = false;
							break;
						}
					}
					
					if ( hit2 ) {
						hit1 = true;
						break;
					}
				}
				
				return hit1;
			}
			else {
				return false;
			}
		}
		
		return true;
	};
	
	/* check is hit referrer */
	jLPO.checkClass.prototype.checkReferrer = function( _referrer ) {
		if ( _referrer != null ) {
			
			if ( document.referrer ) {
				var referrers = _referrer.split( ',' );
				var hit = false;
				var i, len = referrers.length;
				
				for ( i = 0; i < len; i ++ ) {
					referrers[i] = referrers[i].replace( new RegExp( '^\\s+', 'i' ), '' );
					referrers[i] = referrers[i].split( '*' ).join( '[0-9a-z.!?/~#=+*()$_\-]*' );
					
					if ( document.referrer.match( new RegExp( '^' + referrers[i], 'i' ) ) ) {
						hit = true;
					}
				}
				
				return hit;
			}
			else {
				return false;
			}
		}
		
		return true;
	};
	
	/* check URL param */
	jLPO.checkClass.prototype.checkParam = function( _param ) {
		if ( _param != null ) {
			var search = location.search;
			
			if ( search.length > 0 ) {
				search = search.substr(1).split( '&amp;' ).join( '&' );
				
				var params = _param.split( '&' );
				var searches = search.split( '&' );
				var i1, len1 = params.length;
				var i2, len2 = searches.length;
				var hit1 = true;
				var hit2;
				
				for ( i1 = 0; i1 < len1; i1 ++ ) {
					hit2 = false;
					
					for ( i2 = 0; i2 < len2; i2 ++ ) {
						if ( params[ i1 ] == searches[ i2 ] ) {
							hit2 = true;
							break;
						}
					}
					if ( ! hit2 ) {
						hit1 = false;
						break;
					}
				}
				
				return hit1;
			}
			else {
				return false;
			}
		}
		
		return true;
	};
	
	/* check is hit start/end time */
	jLPO.checkClass.prototype.checkTime = function( _side, _time ) {
		if ( _time != null ) {
			var hit = _time.match( new RegExp( '^([0-9]+):([0-9]+)$' ) );
			
			if ( hit ) {
				var date = new Date(
						jLPO.now.getFullYear(),
						jLPO.now.getMonth(),
						jLPO.now.getDate(),
						parseInt( hit[1], 10 ),
						parseInt( hit[2], 10 ), 0, 0 );
				
				if ( ( _side == 'start' && date.getTime() > jLPO.now.getTime() )
				||	( _side == 'end' && date.getTime() <= jLPO.now.getTime() ) ) {
					return false;
				}
			}
			else {
				return false;
			}
		}
		
		return true;
	};
	
	/* check is hit start/end date */
	jLPO.checkClass.prototype.checkDate = function( _side, _date ) {
		if ( _date != null ) {
			var hit = _date.match( new RegExp( '^([0-9]+)\/([0-9]+)\/([0-9]+) ([0-9]+):([0-9]+)$' ) );
			
			if ( hit ) {
				var date = new Date(
					parseInt( hit[1], 10 ),
					parseInt( hit[2], 10 ) - 1,
					parseInt( hit[3], 10 ),
					parseInt( hit[4], 10 ),
					parseInt( hit[5], 10 ), 0, 0 );
				
				if ( ( _side == 'start' && date.getTime() > jLPO.now.getTime() )
				||	( _side == 'end' && date.getTime() <= jLPO.now.getTime() ) ) {
					return false;
				}
			}
			else {
				return false;
			}
		}
		
		return true;
	};
	
	/* check is hit weekday */
	jLPO.checkClass.prototype.checkWeekday = function( _weekday ) {
		if ( _weekday != null ) {
			var table = ['sun','mon','tue','wed','thu','fri','sat'];
			var day = table[ jLPO.now.getDay() ];
			
			var days = _weekday.split( ',' );
			var i, len = days.length;
			var hit = false;
			
			for ( i = 0; i < len; i ++ ) {
				days[i] = days[i].toLowerCase();
				days[i] = days[i].replace( new RegExp( '^\\s+', 'i' ), '' );
				
				if ( days[i] == day ) {
					hit = true;
					break;
				}
			}
			
			return hit;
		}
		
		return true;
	};
	
	/* check area */
	jLPO.checkClass.prototype.checkArea = function( _area ) {
		if ( _area != null ) {
			
			if ( typeof google == 'undefined'
			|| typeof google.loader == 'undefined'
			|| typeof google.loader.ClientLocation == 'undefined'
			|| google.loader.ClientLocation == null ) {
				return false;
			}
			
			var areas = _area.split( ',' );
			var hit = false;
			var i, len = areas.length;
			
			for ( i = 0; i < len; i ++ ) {
				areas[i] = areas[i].replace( new RegExp( '^\\s+', 'i' ), '' );
				
				if ( areas[i] == google.loader.ClientLocation.address.country
				||	areas[i] == google.loader.ClientLocation.address.region
				||	areas[i] == google.loader.ClientLocation.address.city ) {
					hit = true;
					break;
				}
			}
			
			return hit;
		}
		
		return true;
	};
	
})(jQuery);

