// JavaScript Document

var browser = navigator.appName;
var ie = false;

function getjson( url , container, vars )
{
	
	if( vars == null )
	{
		var vars = '';
	}
	
	$('.ajax_loader').fadeIn('fast');
	
	try{
		$.post( url , vars , function( data ){
			
			var json = data;
			
			for( var i = 0 ; i < json.response.length; i++ )
			{
				
				switch( json.response[i].type )
				{
					case 'HTML':
						$( container ).html( json.response[i].data );	
						break;
					case 'SUCCESS':
						success( json.response[i].data );
						break;
					case 'WARNING':
						warn( json.response[i].data );
						break;
					case 'JSCRIPT':
						eval( json.response[i].data );
						break;
				}
				
			}
			
			$('#ajaxloading').hide();
			
		},'json');
	}
	catch(e){
		warn(e);
		$('.ajax_loader').hide();
	}
	
	return false;
	
}

function aj(url,container)
{
	$(".ajax_loader").show();
	
	$.get(url, function(data){
		$(container).html(data);
		$(".ajax_loader").hide();
	});
	return false;
}

function clearfield(elem){
	if(elem.value==elem.defaultValue){
		$(elem).val('');
		$(elem).removeClass('empty');
	}
}


function reset_toggle_prefs()
{
	if ($('#popup_inner #loginform').length > 0) {
		$('#popup_inner #loginform').remove();
		$('#preferences').show();
		init_popup();
	}
	
	toggle_prefs();
	
	return false;
}


function toggle_prefs( callback ){
	
	if( $('#popup_container').css('top') != '-' + $("#popup_container").outerHeight() + 'px' )	{
		
		$("#popup_container").animate(
			{ top: '-' + $("#popup_container").outerHeight() + 'px' }, 
			300,
			false,
			function(){
				//if (ie) {
				 	$('select, object, .mpu, .page_ads').css('visibility','visible');
				//}
				if( callback != undefined )
				{
					eval( callback + '();' );
				}
			}
		 );
		 
	}else{
		
		$("#popup_container").animate(
			{ top:'0px' }, 
			300,
			false,
			function(){
				if( callback != undefined )
				{
					eval( callback + '();' );
				}
			}
		);
		
		//if (ie) {
			$('select, object, .mpu, .page_ads').css('visibility','hidden');
		//}	
	}
	return false;
}

function init_popup(){
	$('#popup_container').css('top','-' + $("#popup_container").outerHeight() + 'px');
	/*$('#popup_preferences').css('height', $("#popup_container").outerHeight() + 'px');*/
}

function init_page(){
	if( browser.indexOf("Internet Explorer") > 0 ){
		ie = true;
	}	
}

function init_menu(){
	
	$('#header_menu ul li').mouseover(function(){
		if ($(this).length > 0) {
			$(this).addClass('active');
			return false;
		}
	});
	
	$('#header_menu ul li').mouseout(function(){
		if ($(this).length > 0) {
			$(this).removeClass('active');
			return false;
		}
	});
	
	$('#header_menu ul li ul li').mouseover(function(){
		if ($(this).length > 0) {
			$(this).parent('ul').parent('li').addClass('active');
			return false;
		}
	});
	
	$('#header_menu ul li ul li').mouseout(function(){
		if ($(this).length > 0) {
			$(this).parent('ul').parent('li').removeClass('active');
			return false;
		}
	});
	
}

function init_search(){
	$('input[name=qcategory]').autoComplete({
		ajax: '/ajax.php?function=json_categories'
	});
	
	$('input[name=postcode]').autoComplete({
		ajax: '/ajax.php?function=json_locations'
	});
}

function pxToInt( str )
{
	var px_pos = str.lastIndexOf('px');
	var i = 0;
	
	if (px_pos > 0) {
		str = str.substring(0, px_pos);
	}
	
	if( str.indexOf('-') == 0 )
	{
		str = str.substring(1,str.length);
		i = 0 - parseFloat( str );
	}
	else
	{
		i = parseFloat( str );
	}
	
	return i;
}

var slideMoving = false;

function init_feeds()
{
	$('.feeds').each(function(){
					var fid = $(this).children('div').attr('title');
						  $(this).load("/loadfeed.php?"+fid ,function(){
					});
	});
	
	$('.controls .left_arrow').click( function(){
		
		if (!slideMoving) {
			
			var margin_left = pxToInt($(this).parent().parent().parent().children('.feed_slider').children('.slide_panel').css('margin-left'));
			var slider_width = $(this).parent().parent().parent().children('.feed_slider').children('.slide_panel').outerWidth();
			
			if (margin_left < 0) {
				
				slideMoving = true;
				
				$(this).parent().parent().parent().children('.feed_slider').children('.slide_panel').animate({
					marginLeft: (margin_left + 220) + 'px'
				}, function(){
					slideMoving = false;
				});
			}
		}
		return false;
	});
	
	$('.controls .right_arrow').click( function(){
		
		if (!slideMoving) {
			var margin_left = pxToInt($(this).parent().parent().parent().children('.feed_slider').children('.slide_panel').css('margin-left'));
			var slider_width = $(this).parent().parent().parent().children('.feed_slider').children('.slide_panel').outerWidth();
			
			var max_margin_left = 0 - (((slider_width / 220) - 1) * 220);
			
			if (margin_left > max_margin_left) {
				
				slideMoving = true;
				
				$(this).parent().parent().parent().children('.feed_slider').children('.slide_panel').animate({
					marginLeft: (margin_left - 220) + 'px'
				}, function(){
					slideMoving = false;
				});
			}
		}
		return false;
	});
	
	$('.controls .plus').click( function(){
		var num_displayed = $(this).parent().parent().parent().children('.feed_slider').children('.slide_panel').children('.feeds:visible').children('.feed_item:visible').length;
		var total_num = $(this).parent().parent().parent().children('.feed_slider').children('.slide_panel').children('.feeds:visible').children('.feed_item').length;
		
		if (num_displayed < total_num) {
			var next_elem = $(this).parent().parent().parent().children('.feed_slider').children('.slide_panel').children('.feeds:visible').children('.feed_item')[num_displayed];
			$(next_elem).slideDown();
		}
		
		return false;
	});
	
	$('.controls .minus').click( function(){
		var num_displayed = $(this).parent().parent().parent().children('.feed_slider').children('.slide_panel').children('.feeds:visible').children('.feed_item:visible').length;
		
		if (num_displayed > 0) {
			var last_elem = $(this).parent().parent().parent().children('.feed_slider').children('.slide_panel').children('.feeds:visible').children('.feed_item')[num_displayed-1];
			$(last_elem).slideUp();
		}
		
		return false;
	});
}

$(document).ready(function(){
	
	init_menu();
	init_page();						   
	init_popup();
	init_search();
	init_feeds();
});


// TOGGLE LOCATIONS
var current_location_id = '';

function toggle_locations(id)
{
	$('.active_tab').removeClass('active_tab');
	
	if( current_location_id != '' )
	{
		$('#location_tab_'+current_location_id).addClass('tab');
		$('#location_'+current_location_id).hide();
	}
	$('.active_location').hide();
	
	$('#location_tab_'+id).removeClass('tab');
	$('#location_tab_'+id).addClass('active_tab');
	
	$('#location_'+id).show();
	current_location_id = id;
	
	return false;
}



// filtering

var keypress = 0;
var cur_field = new Array();
var cur_value = new Array();
var reloading = false;

function run_search(key,name,value){
	
	var container = '#' + name + '_container'; 
	
	if( ( key == keypress ) && ( value != cur_value[cur_field.indexOf(name)] ) ){	
		
		cur_value[cur_field.indexOf(name)] = value;
		
		aj('/ajax.php?function=filter_box&' + name + '=' + value, container )
		return false;
	}
	
}

function filter_box(elem){
	
	var value = encodeURIComponent($(elem).val());
	var name = $(elem).attr('name');
	
	cur_field.push(name);
	
	keypress++;
	setTimeout("run_search(" + keypress + ",'" + name + "','" + value + "')",700);
	
	return false;
}

function get_prefs(){
	
	var pref_array = new Array();
	
	$('#topics :checkbox:checked').each( function(){
		pref_array.push( $(this).attr('name') + '=1' );
	});
	
	return pref_array.join('&');
}

function please_wait()
{
	reloading = true;
	$('#topics').hide();
	$('#details').html('<div class="detail"><label>Please wait for your homepage to reload...</label></div>');
	init_popup();
	toggle_prefs();
}

function show_login()
{
	$('#preferences').hide();
	
	if ($('#popup_inner #loginform').length > 0) {
		$('#popup_inner #loginform').remove();
	}
	
	$('#popup_inner').append( $('#login_box').html() );
	init_popup();
	toggle_prefs();
	
	return false;
}

function reset_profile()
{
	reseting = true;
	$('#topics :checkbox').each( function(){
		$(this).attr('checked','checked');
	});
	save_prefs();
	return false;
}

function save_prefs(){
	
	if (!reloading) {
		var save_data = new Array();
		
		save_data.push(get_prefs());
		save_data.push('function=save_prefs');
		save_data.push('myname=' + encodeURIComponent($('#myname').val()));
		save_data.push('mylocation=' + encodeURIComponent($('#mylocation').val()));
		save_data.push('emailaddress=' + encodeURIComponent($('#emailaddress').val()));
		save_data.push('password_new=' + encodeURIComponent($('#password_new').val()));
		save_data.push('password_confirm=' + encodeURIComponent($('#password_confirm').val()));
		
		geo_lookup_save_prefs(save_data);
	}
	return false;
}

function geo_lookup_save_prefs( save_data )
{
	
	var localSearch = new GlocalSearch();
	var postcode = $("#mylocation").val();
	var resultLat = $("#mylatitude").val();
	var resultLng = $("#mylongitude").val();
	
	localSearch.setSearchCompleteCallback(null, function(){
		if (localSearch.results[0]) {
			resultLat = localSearch.results[0].lat;
			resultLng = localSearch.results[0].lng;
			
			save_data.push('mylatitude='+encodeURIComponent( resultLat ) );
			save_data.push('mylongitude='+encodeURIComponent( resultLng ) );
			
			$('#location_container').removeClass('iserror');
			$('#location_container').addClass('isvalid');
		
		}
		else {
			//alert("Postcode not found");
			$('#location_container').removeClass('isvalid');
			$('#location_container').addClass('iserror');
		}
		

		ajax_save_prefs(save_data);

	});
	
	if ( postcode != '' && ( $('#mylocation').val() != $('#mylocation')[0].defaultValue) ) {
		localSearch.execute( postcode );
	}
	else
	{
		if( $('#mylocation').val() == $('#mylocation')[0].defaultValue )
		{
			save_data.push('mylatitude='+encodeURIComponent( resultLat ) );
			save_data.push('mylongitude='+encodeURIComponent( resultLng ) );
		}
		else
		{
			$('#location_container').removeClass('isvalid');
			$('#location_container').addClass('iserror');
		}
		
		ajax_save_prefs(save_data);
	}
	
}


function ajax_save_prefs( save_data )
{
	$.post('/ajax.php', save_data.join('&'), function(data){
		
		if (data.length > 0) {
			var data = eval(data);
			var error = '';
			var selector = '';
			
			$('.error_msg').remove();
			
			if (data.length > 0) {
				for (var i = 0; i < data.length; i++) {
					
					selector = data[i].field;
					
					if (data[i].field == 'firstname') {
						selector = 'myname';
						error = data[i].error;
						
						$('#popup_container #details').before('<div class="error_msg" id="error_' + selector+ '">' + error + '</div>');
					}
					else {
						if (data[i].error == 'Already being used') {
							error = 'This email address is already in use. If you have already registered please <a href="/login?email=' + encodeURIComponent($('#' + selector).val()) + '">click here to login</a>';
						}
						else {
							error = data[i].error;
						}
						
						$('#popup_container #' + selector).after('<div class="error_msg" id="error_' + selector+ '">' + error + '</div>');
						
					}
					
				}
			}
		}
		else {
			if( $('#popup_container').css('top') != '-' + $("#popup_container").outerHeight() + 'px' ){
				toggle_prefs( 'please_wait' );	
			}else{
				please_wait();
			}
			window.location = window.location;
		}
		
	});
}
