var state 			= "cancel";
var hiddenheight 	= '-100px';
var baseurl			= '';
var ignoreurl 		= '';
var ignorecount 	= 0;


function prep_login() {
	state = "login";
	$('#btncancel').fadeOut('fast',function() {
		$('div#logindialog div.buttons').fadeIn('fast');
	});
}

function prep_cancel() {
	state = "cancel";
	$('div#logindialog div.buttons').fadeOut('fast',function() {
		$('#btncancel').fadeIn('fast');
	});
}


function init_file_style() {
	$("input[type=file]").filestyle({ 
		image: "assets/img/btnbrowse.gif",
		imageheight : 13,
		imagewidth : 19,
		width : 150
	});
}





function strrpos (haystack, needle, offset) {
    // Finds position of last occurrence of a string within another string  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/strrpos
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // *     example 1: strrpos('Kevin van Zonneveld', 'e');
    // *     returns 1: 16
    var i = (haystack+'').lastIndexOf( needle, offset ); // returns -1
    return i >= 0 ? i : false;
}


function substr (f_string, f_start, f_length) {
    // Returns part of a string  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/substr
    // +     original by: Martijn Wieringa
    // +     bugfixed by: T.Wild
    // +      tweaked by: Onno Marsman
    // *       example 1: substr('abcdef', 0, -1);
    // *       returns 1: 'abcde'
    // *       example 2: substr(2, 0, -6);
    // *       returns 2: ''
    f_string += '';

    if (f_start < 0) {
        f_start += f_string.length;
    }

    if (f_length == undefined) {
        f_length = f_string.length;
    } else if (f_length < 0){
        f_length += f_string.length;
    } else {
        f_length += f_start;
    }

    if (f_length < f_start) {
        f_length = f_start;
    }

    return f_string.substring(f_start, f_length);
}







function init_login() {
	
	// hide login button and provide cancel button
	$('div#logindialog div.buttons').after('<a id="btncancel" href="#"><img src="assets/img/btncancel.png" alt="Cancel" /></a>').hide();
	
	// hook cancel button
	$('a#btncancel').click(function() {
		$('div#logindialog').animate({top:hiddenheight},{
				duration:450, 
				easing:'easeOutQuad', 
				complete: function() { 
					$('a#btnlogin').fadeIn('fast');
				}
			});
		return false;
	});
	
	// adjust the dialog css and hide it
	$('div#logindialog').addClass('rolled').css('top',hiddenheight);
	
	
	
	
	// ================
	// = INITIAL HOOK =
	// ================
	
	// add the fancy login trigger button hook
	$('div#content div.inner').prepend('<a id="btnlogin" href="#"><img src="assets/img/btnlogin.png" alt="Log In" /></a>');
	
	// hook the hook
	$('a#btnlogin').click(function() {
		$('a#btnlogin').fadeOut('fast');
		$('div#logindialog').animate({top:0},{
				duration:450, 
				easing:'easeOutQuad',
				complete: function() {
					$('#logindialog input#quick_email').focus();
					$('#logindialog input#quick_email').keyup(function() {
						if($(this).attr('value').length!=0) {
							if(state != "login") {
								prep_login();
							}
						} else {
							if(state != "cancel") {
								prep_cancel();
							}
						}
					});
				}
			});
		return false;
	});
}



function get_url_root(url, index) {
	my_index = strrpos(url,index);
	return substr(url, 0, my_index+index.length);
}

function get_url_var(url, index) {
	return substr(url,my_index+index.length,url.length);
}


function hook_pagination() {
	
	$('body').append('<div id="holding" class="hidden"><ul></ul></div>');
	
	// ajax pagination
	$('p.pagination a').live('click', function() {
		pagination_link = $('p.pagination a');
		pagination_link.fadeTo('normal',0);
		$('ol#suggestions').append('<li id="loading"><span><img src="' + baseurl + 'assets/img/loading.gif" alt="Loading..." /></span></li>');
		// display loader
		$('ol#suggestions li#loading').hide().slideDown(function() {
			// load data via AJAX
			
			if(ignorecount==0)
			{
				// nothing to modify
				targeturl = pagination_link.attr('href');
			}
			else
			{
				// user ignored at least one site, so our LIMIT will be off unless we take it into account
				targeturl = pagination_link.attr('href') + '/adjustment/' + ignorecount;

				// cleanup
				ignorecount = 0;
			}
			
			$('div#holding ul').load(targeturl + ' ol#suggestions li', function() {
				
				// need to check if we're editing
				if($('ol#suggestions').hasClass('edit')) {
					$('div#holding ul li').each(function() {
						site_id = substr($(this).attr('id'),4,$(this).attr('id').length);
						$(this).prepend('<a class="ignore" href="' + ignoreurl + '/' + site_id + '"><img src="' + baseurl + 'assets/img/icon-delete.gif" alt="Ignore" /></a>');
					});
				}
				
				// go ahead and move our results
				$('ol#suggestions').append($('div#holding ul').html());
				
				// clean up the loader and update the pagination link
				$('li#loading').slideUp(function() {
					$('div#holding').empty().append('<ul></ul>');
					
					// need to modify the pagination href
					ref_URL = pagination_link.attr('href');
					ref_index = 'page/';
					root_URL = get_url_root(ref_URL,ref_index);
					current_page = get_url_var(ref_URL,ref_index);
					new_page = Math.floor(current_page) + 1;
					pagination_link.attr('href',root_URL + new_page);
					pagination_link.fadeTo('normal',1);
					
				}).remove();
			});
		});
		return false;
	});
	
}


function hook_sweet_editing() {
	$('a#trigger_edit').bind('click', function() {
		$('a#trigger_edit').unbind('click');
		
		// hide the default message
		$('a#trigger_edit').parent().fadeTo('fast', 0, function() {
			$('a#trigger_edit').parent().css('visibility','hidden');
		});
		
		// roll down the dialog
		$('div#editdialog').animate({top:0},{
			duration:450, 
			easing:'easeOutQuad',
			complete: function() {
				$('ol#suggestions').addClass('edit').addClass('alt');
				// prepend all of the ignore icons
				$('ol#suggestions li').each(function() {
					siteid = substr($(this).attr('id'),4,$(this).attr('id').length);
					$(this).prepend('<a class="ignore" href="' + ignoreurl + '/' + siteid + '/ajax/true"><img src="' + baseurl + 'assets/img/icon-delete.gif" alt="Ignore" /></a>');
					$('a.ignore').css('width','0').animate({width:20},{
						duration:250,
						queue:false,
						easing:'easeOutQuad',
						complete: function() {
							// ignore links are hooked later on, we just want to hide the dialog and show the original message
							$('#done_edit').bind('click', function() {
								$('#done_edit').unbind('click');
								$('div#editdialog').animate({top:hiddenheight},{
										duration:450, 
										easing:'easeOutQuad',
										complete: function() {
											// restore the original message...
											$('ol#suggestions').removeClass('edit');
											// clean up the ignore icons...
											$('ol#suggestions li a.ignore').animate({width:0}, {
													duration:150,
													queue:false,
													easing:'easeOutQuad'
												});
											$('a#trigger_edit').parent().css('visibility','visible').fadeTo('normal',1, function() {
												$('ol#suggestions li a.ignore').remove();
												setTimeout(hook_sweet_editing,300);
											});
										}
									});
								return false;
							});
						}
					});
				});
			}
		});
		return false;
	});
}





$(document).ready(function() {
	
	baseurl = $("meta[name='baseurl']").attr('content');
	ignoreurl = $("meta[name='ignoreurl']").attr('content');
	
	init_file_style();
	
	if($('div#logindialog').length!=0) {
		// handle login page
		init_login();
	}
	
	if($('ol#suggestions').length!=0) {
		hook_pagination();
		
		// prep the edit interaction
		$('#content').prepend('<div class="dialog" id="editdialog"><div class="actions"><p class="note">Please ignore the sites you\'d like to omit from future suggestions</p><a href="#" id="done_edit"><img src="' + baseurl + 'assets/img/btndone.png" alt="Done" /></a></div></div>');
		$('#editdialog').addClass('rolled').css('top',hiddenheight);
		
		// hook the edit button
		hook_sweet_editing();
		
		// hook the ignore buttons
		$('a.ignore').live('click',function() {
			ignorecount++;
			ignore_button = $(this);
			ignore_button.parent().slideUp(function() {
				ignore_button.parent().remove();
			});
			$.ajax({
				url: ignore_button.attr('href')
			});
			return false;
		});
	}
	
	
});


