jQuery(function() {	

	// Report Issue
	$('#submit_issue').click(function() {

		var email = $('#report_email').val();
		
		var re = /^\w+([\.-]?\w+)*@(\w+(-?\w+)*\.)+[A-Za-z]{2,6}$/;
		if (re.test(email) != 1) {
			alert('Invalid E-mail');
			return;
		}
		alert($('#report_issuedscribe').val());

		var data = {
			'email':$('#report_email').val(),
			'name':$('#report_name').val(),
			'issueType':$('#report_issueType').val(),
			'issuedscribe':$('#report_issuedscribe').val()		
		};

		$.post('sendreportissue.php',data, function() {
			$('#report_stat').text('Your issue was sent successfully. Thank You');
		});
		
	});


	// Tell Friends
	$('#tell_friends').click(function() {

		var send = true;

		var email = $('#tell_email').val();
		var femail;
		var friend_emails;
		
		var re = /^\w+([\.-]?\w+)*@(\w+(-?\w+)*\.)+[A-Za-z]{2,6}$/;
		if (re.test(email) != 1) {
			alert('Invalid E-mail');
			send = false;
		}

		var multi = false;
		var t = $('#friend_emails').val();
		if (t.indexOf(';') > -1) { var emails = t.split(';'); multi = true; }
		else if (t.indexOf(',') > -1) { var emails = t.split(','); multi = true; }
		else {		
			femail = $.trim(t);
			if (re.test(email) != 1) {
				alert('Invalid Friends E-mail');
				send = false;
				return;
			}
		}

		if (multi) {

			var fe =[];
			$.each(emails, function() {
				var email = $.trim(this);
				if (re.test(email) != 1) {
					alert('Invalid Friends E-mail');
					send = false;
					return;
				}
				fe.push(email);
			});
			friend_emails = fe.join(';');
		}
		else { friend_emails = femail; }

		if (!send) { return; }

		//$(this).attr('disabled', 'true');

		var data = {
			'email':$('#tell_email').val(),
			'name':$('#tell_name').val(),
			'friend_emails':friend_emails,
			'comments':$('#tell_comments').val()		
		};

		$('#tell_stat').text('Sending ...');

		$.post('tell_friends.php',data, function() {
			$('#tell_stat').text('Emails sent to your friends. Thank You');
		});
		
	});


	$('.srch').click(function() {
		
		var qstr = $('#search_box').val();
		var site = this.id;

		// Make history entry
		HistoryManager.append(qstr);

		// Search
		SearchManager.search(site, qstr);

	});	
	
	var help;
	var eula = false;
	var about = false;
	var info_on = false;


	$('#main').click(function(e) {

		/****** Info box events ****/

		var tid = e.target.id;

		if (tid.indexOf('info') > -1) {

			setTimeout(scrollTo, 0, 0, 1);
		
			// The Back button was clicked
			if (tid == 'info_back') {


				// Default face, time to close
				if (!InfoBox.face) { $('#info_div').animate({top:480}, 500); info_on = false; }
				else {

					if ((eula) || (help) || (about)) {
						$('#main').height(420);
						$('#info_div').height(480);
						$('#info_content').height(365);
						$('.info_txt').height(324);
						eula = false;
						help = false;
						about = false;
					}
	

					if (window.orientation) { $('#info_scroller').animate({left:11}, 500); }
					else { $('#info_scroller').animate({left:8}, 500); }

					InfoBox.face = 0;

					$.each(InfoBox.titles, function() { $(this).addClass('dn'); });
					$('#info_title_info').removeClass('dn');
				}
			}

			if (tid.indexOf('info_li') > -1) {

				$.each(InfoBox.faces, function() {
					$(this).addClass('dn');
				});

				var t = tid.split('_');
				var tdiv = '#info_'+t[2];

				$(tdiv).removeClass('dn');

				if (t[2] == 'eula') {
					$('#main').height(4170);
					$('#info_div').height(4200);
					$('#info_content').height(4170);
					$('.info_sub').height(4070);
					$('.info_txt').height(4070);

					eula = true;
				}
				else if (t[2] == 'help') {
					$('#main').height(1770);
					$('#info_div').height(1800);
					$('#info_content').height(1770);
					$('.info_sub').height(1670);
					$('.info_txt').height(1670);

					help = true;
				}
				else if (t[2] == 'about') {
					$('#main').height(480);
					$('#info_div').height(540);
					$('#info_content').height(425);
					$('.info_sub').height(384);
					$('.info_txt').height(384);

					help = true;
				}

				if (window.orientation) { $('#info_scroller').animate({left:-450}, 500); }
				else { $('#info_scroller').animate({left:-300}, 500); }

				InfoBox.face = 1;

				$.each(InfoBox.titles, function() { $(this).addClass('dn'); });
				tdiv = '#info_title_'+t[2];
				$(tdiv).removeClass('dn');

			}

			return;
		}



		if ((tid != 'dot_0') && (tid != 'dot_1') && (tid != 'dots') && (tid != 'left') && (tid != 'right')) { return; }

		$('#main').height(420);

		if (ScrollTracker.active) { return; }


		var em = ($('#main').width()/2);
		var el = e.clientX;		

		ScrollTracker.currentFace = (!ScrollTracker.currentFace);
		if (ScrollTracker.currentFace) {
			$('#dot_0').attr('src', 'img/dot0.png');
			$('#dot_1').attr('src', 'img/dot1.png');
		} else {
			$('#dot_0').attr('src', 'img/dot1.png');
			$('#dot_1').attr('src', 'img/dot0.png');
		}

		var ld = ScrollTracker.direction;

		// Left or Right?
		if (el > em) { ScrollTracker.direction = 0;	}
		else if (el < em) { ScrollTracker.direction = 1; }

		if (ScrollTracker.firstRun) {
			ScrollTracker.firstRun = false;
			ScrollTracker.lastDirection = ScrollTracker.direction;
		} else {
			if (ld != ScrollTracker.direction) { ScrollTracker.lastDirection = false; }
			else { ScrollTracker.lastDirection = true; }
		}
		setTimeout(function() { $('#main').height(400); }, 500);
		setTimeout(scrollTo, 0, 0, 1);
		AnimationManager.scroll();
		ScrollTracker.active = true;

	});

	// Left options	- location/history
	$('#sel_l').change(function() {
		if ($(this).val() == 'def') { return; }
		var qstr = $(this).val();
		if (qstr == 'loc') { if (loc = promptLocation()) { UserLocation.set(loc); } }
		else if (qstr == 'clear_history') { HistoryManager.clear(); }
		else if (qstr == 'clear_field') { $('#search_box').val(''); }
		else { $('#search_box').val(qstr); }
		setTimeout(function() { $('#sel_l').val('def'); }, 100);

	});


	// Right options - site type prefrebce
	$('#sel_r').change(function() {
		SiteType.set($(this).val());
	});

	$('#search_box, .sel').blur(function() { setTimeout(scrollTo, 0, 0, 1); });

	$('#search_box').focus(function() {
		if ($(this).val() == 'Enter your search here') { $(this).val(''); }	
	});



	// Display the History items
	HistoryManager.setup();
	// Site type preferebnce
	SiteType.setup();

	// Fill InfoBox faces
	InfoBox.faces = [$('#info_about'), $('#info_help'), $('#info_eula'), $('#info_report'), $('#info_tell')];
	InfoBox.titles = [$('#info_title_info'), $('#info_title_about'), $('#info_title_help'), $('#info_title_eula'), $('#info_title_report'), $('#info_title_tell')];

	// Hide address bar, adjust icons area etc
	reOrient();
	setTimeout(scrollTo, 0, 0, 1);

});


// Class to manage Location 
var UserLocation = {
	
	CN:'location',
	
	set:function(loc) {
		if (!$.cookie(this.CN)) { $.cookie(this.CN, loc); }
		else { $.cookie(this.CN, loc); }
	},
	
	get:function() {
		if (!$.cookie(this.CN)) { return ''; }
		else { return $.cookie(this.CN); }
	}
};


// Class to manage website preference
var SiteType={

	CN:'website_type',

	set:function(type) {
		if (!$.cookie(this.CN)) { $.cookie(this.CN, type); }
		else { $.cookie(this.CN, type); }		
	},
	
	get:function() { return $.cookie(this.CN); },
	
	setup:function() {
		if (!$.cookie(this.CN)) { $.cookie(this.CN, 'mob'); }
		$('#sel_r').val(this.get());
	}
};


// Class to Manage history
var HistoryManager={

	// Number of History items
	HL:5,
	//Cookie Name
	CN:'history',

	// Make new history entry
	append:function(qstr) {

		if ((qstr == '') || (qstr == 'Enter your search here')) { return; }

		var qstr = escape($.trim(qstr));
		var dup = false;


		// Cookie doesn't exit, create it
		if (!$.cookie(this.CN)) { $.cookie(this.CN, qstr); }

		else {
		
			var cd = $.cookie(this.CN).split('"');
			if (cd.length < this.HL) {
				// No duplicate entries!
				$.each(cd, function() { if ((qstr == this) || (qstr.toLowerCase() == this.toLowerCase())) { dup = true; }});
				if (!dup) { cd.push(qstr); }
			} else {
				// No duplicate entries!
				$.each(cd, function() { if ((qstr == this) || (qstr.toLowerCase() == this.toLowerCase())) { dup = true; }});

				if (!dup) {
					cd.shift();
					cd.push(qstr);
				}
			}
			
			var ca = cd.join('"');

			// Update the cookie
			$.cookie(this.CN, ca);

		}

		if (!dup) {
			var op = '<option value="'+unescape(qstr)+'">'+unescape(qstr)+'</option>';
			if ($('#sel_l').children().length == 4) { $('#sel_l').append(op); }
			else { $('#sel_l option:nth-child(5)').before(op); }
		}
	},
	
	// Append the contents of cookie to DOM
	setup:function() {

		if (!$.cookie(this.CN)) { return; }
		else {
			var cd = $.cookie(this.CN).split('"');
			$.each(cd, function() {
				var qstr = unescape(this);
				var op = '<option class="srch_str" value="'+qstr+'">'+qstr+'</option>';
				if ($('#sel_l').children().length == 4) { $('#sel_l').append(op); }
				else { $('#sel_l option:nth-child(5)').before(op); }
			});
		}
	},
	
	// Clear the history conents
	clear:function() {

		if (!$.cookie(this.CN)) { return; }
		else { $.cookie(this.CN, ''); }

		var op = '#sel_l option:nth-child(5)';
		while ($('#sel_l').children().length > 4) { $(op).remove(); }
	}

};


// Location info store

function promptLocation() {
	var loc;
	var p = true;
	while (p) {
		var loc = prompt('Enter your ZIP code or city', UserLocation.get());
		if (loc === null) {
			p = false;
			return false;
		} else if (((loc.length == 5) && (!isNaN(parseInt(loc)))) || ((loc.length > 0) && (isNaN(parseInt(loc))))) {
				p = false;
				return loc;
		}
	}
}

// Info panel ON||OFF
var info_on = false;

// Handle events are element on reorientation
function reOrient(e) {
	
	// No matter what, hide the addressbar
	setTimeout(scrollTo, 0, 0, 1);

	var orient = window.orientation;

	// Portrait
	if (orient == 0) {
		
		$('#main').width(300);

		$('#buttons_grid, .grid').width(297);
		$('#buttons_grid, .grid').height(235);
		ScrollTracker.orientation = 0;
		$('.img_nav').css('top', 300);
		$('#dots').css('width', 300);
		$('#dots').css('top', 303);

		$('.srch').css('margin-left', 12);

		$('.ad').width(288);

		$('#info_div').width(320);
		$('#info_content').width(287);
		$('ul').width(285);
		$('li').css('background-position', 260);
		$('.info_sub').css('margin-left', 17).width(275);
		$('.info_txt').width(275).height(324);

	}
	// Landscape
	else if (orient == 90) {

		$('#main').width(460);

		$('#buttons_grid, .grid').width(457);
		$('#buttons_grid, .grid').height(157);
		ScrollTracker.orientation = 90;
		$('.img_nav').css('top', 220);
		$('#dots').css('width', 460);
		$('#dots').css('top', 220);

		$('.srch').css('margin-left', 14);

		$('.ad').width(430);

		$('#info_div').css('width', 480);
		$('#info_content').css('width', 478);
		$('ul').width(445);
		$('li').css('background-position', 416);
		$('.info_sub').css('margin-left', 173).width(400);
		$('.info_txt').width(427).height(174);		
	}

	AnimationManager.adjust();
}



// Info box info

var InfoBox={
	face:0,
	sub:'info_about',
	faces:[], // scrolling faces
	title:[] // title images
}



setTimeout(scrollTo, 0, 0, 1);
