// JavaScript support functions for site
//custom error handling
javascript_debug = false;
window.onerror = function (msg, url, line){
	jQuery.post("index.php?controller=ErrorReporting&method=javascript", { msg: msg, url: url, line: line });
	if(javascript_debug){
		console.debug({ msg: msg, url: url, line: line })
	}
	return true;
}

function debug(msg){
	if(!javascript_debug) return false;
	jQuery('body').append(msg);
}
	
	// If you delete these, you WILL DIE. Plain and simple.
	function toggleShowContainer(elementId)
	{
		container = document.getElementById(elementId);
		if ( container.style.display == 'none' ) {
			Effect.BlindDown(elementId, {duration:0.5});
		} else {
			Effect.BlindUp(elementId, {duration:0.5});
		}
	}

	function toggleShowHideBlock(elementId)
	{
		container = document.getElementById(elementId);
		if ( container.style.display == 'none' ) {
			showBlock(elementId);
		} else {
			hideBlock(elementId);
		}
	}
	// Why risk it, really?
	
	// this function will be used for scrolling bar
	function tog_game_icon(game_to_show)
	{
		var parent = jQuery('#game_icons .game_icons').eq(0);
		var cur = jQuery('.game_icons_block.current');
		var tog = jQuery("#game_icons .game_icons_block").eq(game_to_show);
		var fade_duration = 500;

		//cancel conditions
		if(parent.hasClass('fading')) {return false}; 	//fade already in progress
		if(tog.hasClass('current')) {return false;} 	//already active
		
		//alert(cur.attr('id')+' to be faded out over '+fade_duration);
		//alert(cur.fadeOut);
		
		parent.addClass('fading'); 					//notate fade in progress
		jQuery(cur).fadeOut(fade_duration, function(){ 		//fade out current tab
			//alert('cur faded');
			cur.removeClass('current');				//swap 'current' class from existing...
			tog.addClass('current');				//...to new 
			tog.fadeIn(fade_duration, function(){ 	//fade in the new tab
				parent.removeClass('fading');		//notate fade no longer in progress
			});
		});		
	}
	
	function toggleShowContainer(elementId)
	{
		var whichVar = 'hasBeenResized'+elementId;
		container = document.getElementById(elementId);
		if ( container.style.display == 'none' ) {
			Effect.BlindDown(elementId, {duration : 0.5});
			window[whichVar] = 1;
		} else {
			Effect.BlindUp(elementId, {duration : 0.5});
			window[whichVar] = -1;
		}
	}

	function toggleFixHeight(internalDiv,externalDiv)
	{
		var whichVar = 'hasBeenResized'+internalDiv;
		var origHI = 'origH_int_'+internalDiv;
		var origHE = 'origH_ext_'+internalDiv;
		
		if (window[whichVar] == -1) {
			document.getElementById(externalDiv).style.height='auto';
		} else if (window[whichVar] == 0) {
			var intH=document.getElementById(internalDiv).offsetHeight;
			var newH = parseInt(window[origHE]) + parseInt(intH) + 20;
			document.getElementById(externalDiv).style.height = newH+"px";
			// Do nothing, stay the same
		} else {
			var extH=document.getElementById(externalDiv).offsetHeight;
			var intH=document.getElementById(internalDiv).offsetHeight;
			var newH = parseInt(extH) + parseInt(intH) + 20; // Plus 20 px for good measure
			window[whichVar] = 0;
			window[origHE] = extH;
			window[origHI] = intH;
			document.getElementById(externalDiv).style.height = newH+"px";
		}
	}
		
	function deleteEvent(eventId, feedType)
	{
		if(confirm('Are you sure you want to DELETE this event? It will be gone forever.')) {
			xajax_Event_deleteEvent(eventId,feedType);
		}
	}
	
	//events to be fired when the document is ready
	jQuery(document).ready(function(){ 	
		init_external_links();		//should be towards the top, such that if any following scripts fail, this still takes place
		init_toggleable_boxes();
		app.init_group_search();
	});
	
	//external links open in a new window
	function init_external_links(){
		jQuery('A[rel="external"]').click(function(){
			window.open(jQuery(this).attr('href'));
			return false;
    	});
	}
	
	function init_toggleable_boxes(){
		var slide_speed = 300;
		jQuery('.toggle').removeClass('toggle').addClass('toggleable');
		jQuery('.toggleable h1')
			.append('<span class="toggle_icon"></span>')
			.click(function(){
				jQuery(this).parents('.toggleable').eq(0).find('.content-box-body').eq(0).slideToggle(slide_speed);
			})
		;

	}
	
	//this function is called after a user's profile is loaded via ajax
	function account_profile_loadcomplete(){
		app.stat_tracker_init();
	}
		
function app(){
	this.rotators = Array();
	
	this.init = function(){
		jQuery(document).ready(function(){
			app.init_rotators();
		});
	}
	
	this.init_rotators = function(){
		jQuery('.rotator').each(function(i){
			app.rotators[i] = new Rotator(this, i);
		});
	}
	
	this.init_group_search = function(){
		if(jQuery('#group_search').length > 0) { 
			this.group_search = new group_search
		} else {
			return false;
		}
	}
	
	this.stat_tracker_init = function(){
		//initialize stat tracker nav with jcaraousel
			jQuery('#game_icon_nav').jcarousel();
			jQuery('#game_icon_nav .game_art')
				.click(function(){
					var index = jQuery("#game_icon_nav .game_art").index(this);
					tog_game_icon(index);
				})
				.hover(function(){
					jQuery('#current_game_name').text(this.title);
				})
				.mouseout(function(){
					jQuery('#current_game_name').text('Select a game above');
				});
		this.wow_stats = new wow_stats;
	}
	
	function wow_stats(){
		this.characters = Array(); //for caching
		
		this.add_character_show = function(){
			jQuery('#characterPickerForm').show();
			jQuery('#add_character_link').hide();
		}
		
		this.add_character_hide = function(){
			jQuery('#characterPickerForm').hide();
			jQuery('#add_character_link').show();
		}
		
		this.add_character = function(region, realm, name){
			//fatal error: no name provided
			if(name == '') return false;
			
			//fatal error: add already in progress
			add_link = jQuery('#characterPickerForm a.add');
			if(add_link.text() == '[ Adding... ]') { return false;}
			
			//notify: adding...
			add_link.text('[ Adding... ]');
			
			//make server request
			callback = "app.wow_stats.add_character_complete";
			xajax_WowArmory_addCharacter(region, realm, name, callback);
		}
		
		this.add_character_complete = function(content, character_id){
			jQuery('#characterPickerForm a.add').text('[ Add ]');
			
			//fatal error: an id wasn't returned, alert the message and leave
			if(!character_id) {alert(content); return false;}

			jQuery('#world_of_warcraft_stats ul.characters').append("<li id='character_"+character_id+"' class='character_info'>"+content+"</li>");
			jQuery('#character_'+character_id+' .view_all').hide();
			jQuery('#character_'+character_id).hide(); //hide the character, because we're going to animate it in
			
			track_your_stats = jQuery('#wowcontent .track_your_stats');
			
			if(track_your_stats.length > 0){
				track_your_stats.slideUp('slow', function(){
					jQuery('#character_'+character_id).slideDown();
				});
			} else {
				jQuery('#character_'+character_id).slideDown();
			}
			
		}
		
		this.init_character_view = function(){
			//replace stat dropdowns with styleable markup
				jQuery('#world_of_warcraft_stats select').styledSelect();
			//bind the change functionality to left
				jQuery('#world_of_warcraft_stats .left_details select').change(function(){
					target_class = this.value.toLowerCase().replace(/ /, '_'); 												//'Base Stats' becomes 'base_stats'
					jQuery('#world_of_warcraft_stats .left_details li.detail_box_active').removeClass('detail_box_active');	//hide current stats
					jQuery('#world_of_warcraft_stats .left_details li.'+target_class).addClass('detail_box_active'); 		//show selected stats
				});
			//bind the change functionality to right (same as above)
				jQuery('#world_of_warcraft_stats .right_details select').change(function(){
					target_class = this.value.toLowerCase().replace(/ /, '_'); 
					jQuery('#world_of_warcraft_stats .right_details li.detail_box_active').removeClass('detail_box_active');
					jQuery('#world_of_warcraft_stats .right_details li.'+target_class).addClass('detail_box_active');
				});
		}
		
		this.view_character = function(CharacterId){
			if(this.characters[CharacterId] != undefined){ //do we have the data cached?
				this.load_character_complete(this.characters[CharacterId], CharacterId); //load from cache
			} else {
				this.load_character(CharacterId); //load from server
			}
		}
		
		this.load_character = function(CharacterId){
			//load the data from the server
			xajax_WowArmory_viewProfile(CharacterId, 'app.wow_stats.load_character_complete'); // second param is the function to be called upon completion
		}
		
		this.load_character_complete = function(content, CharacterId){
			if(this.characters[CharacterId] == undefined){
				this.characters[CharacterId] = content; //if it's not cached, cache it
			}
			jQuery('#wow_character_details_container').html(content).show();					//dump in the content and show it
			jQuery('#world_of_warcraft_stats ul.characters .character_info').hide();			//hide all characters previews except...
			jQuery('#world_of_warcraft_stats ul.characters #character_'+CharacterId).show();	//show the relevant character
			jQuery('#world_of_warcraft_stats ul.characters .view').hide(); 						//hide the view links
			jQuery('#add_character_link, #characterPickerForm').hide();							//hide add characters link and form
			jQuery('#world_of_warcraft_stats ul.characters .view_all').show(); 					//show the view all link
			jQuery('#world_of_warcraft_stats ul.characters .remove').hide();					//hide the remove links
			jQuery('#world_of_warcraft_stats ul.characters .update').hide();					//hide the update links
			this.init_character_view();
		}

		this.remove_character = function(character_id){
			callback = 'app.wow_stats.remove_character_complete';
			xajax_WowArmory_removeCharacterByCharacterId(character_id, callback);
		}
		
		this.remove_character_complete = function(character_id){
			jQuery('#character_'+character_id).slideUp(500, function(){jQuery('#character_'+character_id).remove();});
		}
		
		this.show_character_list = function(){
			jQuery('#world_of_warcraft_stats ul.characters .character_info').show(); 	//show all character previews
			jQuery('#wow_character_details_container').hide(); 							//hide the detailed stats
			jQuery('#world_of_warcraft_stats ul.characters .view').show(); 				//hide the view links
			jQuery('#world_of_warcraft_stats ul.characters .remove').show();			//show the remove links
			jQuery('#world_of_warcraft_stats ul.characters .update').show();			//show the update links
			jQuery('#add_character_link').show();										//show add character link
			jQuery('#characterPickerForm').hide();										//hide add character link
			jQuery('#world_of_warcraft_stats ul.characters .view_all').hide();			//hide the view all links
		}
		
		this.update_character = function(character_id){
			update_link = jQuery('#character_'+character_id+' .update');
			
			//fatal error: update in progress
			if(update_link.text() == '[ Updating... ]') return false;
			//notify: updating...
			update_link.text('[ Updating... ]')
			
			//make server request
			callback = 'app.wow_stats.update_character_complete';
			xajax_WowArmory_updateCharacterByCharacterId(character_id, callback);
		}
		
		this.update_character_complete = function(content, character_id){
			jQuery('#character_'+character_id).html(content);	//update the char in the list
			this.show_character_list();							//show the character list in order to hide the "view all" link and get to a knowable state (ie don't show "view all" if the character view is already displayed)
			this.characters[character_id] = null; 				//clear the cache so it'll be reloaded when viewed
			//notify: updated
			jQuery('#character_'+character_id+' .update').text('[ Updated! ]').delay(1500, function(){
				jQuery('#character_'+character_id+' .update').text('[ Update ]')
			});
		}
		
		//constructor calls here
		jQuery('#world_of_warcraft_stats ul.characters .view_all').hide();	//hide the view all links
		jQuery('#characterPickerForm').hide();
	}

	function group_search(){
		//variables relating to search
		this.query = '';								//the text search
		this.channel_id = jQuery.query.get('channel');	//grabbing value for $_GET['channel'] via jquery plugin 'query' 
		this.page = 1;
		this.order_by = 'members';						//name of the column to sort by
		this.ascending = false;							//whether the order is to be ascending (or descending)
		this.last_30_days = false;						//whether to show only groups active within 30 days
		
		//other variables for internal use
		this.updating = false;
		this.html_element = jQuery("#game_group_search_results");
		
		this.initialize_html = function(){
			//bind functionality to html elements
			
			//form submit
			this.html_element.find('form').submit(function(event){
				event.preventDefault();
				$form = jQuery(this);
				$form_query = $form.find('#gameGroupSearchKeywords');
				form_query_val = $form_query.val() == $form_query.attr('default_text') ? '' : $form_query.val();
				form_last_30_days_val = $form.find('#show_active').attr('checked') ? true : false;
				
				//fatal error: no change
				if(form_query_val == app.group_search.query && form_last_30_days_val == app.group_search.last_30_days) {
					return false;
				}
				
				app.group_search.query = form_query_val;
				app.group_search.last_30_days = form_last_30_days_val;
				app.group_search.page = 1;
				app.group_search.update_results();
			});
			
			form_query = this.html_element.find('#gameGroupSearchKeywords')
				.attr('default_text', 'Search group name, owner, tags')
				.focus(function(event){
					$this = jQuery(this);
					if($this.val() == $this.attr('default_text')){
						$this.attr('value', '');
					}
				})
				.blur(function(event){
					$this = jQuery(this);
					if($this.val() == ''){
						$this.attr('value', $this.attr('default_text'));
					}
				})
				
			if(form_query.attr('value') == '') form_query.attr('value', form_query.attr('default_text'));
			//onfocus="if (this.value == '{$defaultGroupSearchQuery}') this.value = '';" onblur="if (this.value == '' || this.value == '{$defaultGroupSearchQuery}') this.value = '{$defaultGroupSearchQuery}';"
			
			//sorting
			this.html_element.find('th a').click(function(event){
				event.preventDefault();
				app.group_search.sort_by_column(this.className); //we expect the css class names to match their column names
			});
			
			//pagination
			this.html_element.find('.paging_next').click(function(event){
				event.preventDefault();
				app.group_search.next_page();
			});
			//pagination
			this.html_element.find('.paging_prev').click(function(event){
				event.preventDefault();
				app.group_search.previous_page();
			});
		}
		
		this.column_is_ascending = function(column){
			var ascending = false;
			if(column == this.order_by){ 	//not our first time sorting by this column; just invert the existing value
				ascending = !this.ascending;
			} else { 						//our first time sorting by this column
				switch(column){ 			//default sorting per column
					//ascending cases
					case 'name':
						ascending = true;
						break;
					//everything else is descending
					default:
						ascending = false;
				}
			}
			return ascending ? true : false;
		}
		
		this.next_page = function(){
			//fatal error: load already in progress
			if(this.is_updating()) return false;
			
			this.page++;
			this.update_results();
		}

		this.previous_page = function(){
			//fatal error: already at start, or update in progress
			if(this.page==0 || this.is_updating()) return false;
			
			this.page--;
			this.update_results();
		}

		this.sort_by_column = function(column){
			//fatal error: load already in progress
			if(this.is_updating()) return false;
			
			this.page=1;
			this.ascending = this.column_is_ascending(column);
			this.order_by = column;
			this.update_results();
		}
		
		this.update_results = function(){
			this.is_updating(true);
			var order = this.ascending? "asc" : "desc";
			var last_30_days = this.last_30_days ? 30 : null;
			xajax_Channel_gameGroupsSearch(this.query, this.channel_id, this.page, this.order_by, order, last_30_days, "app.group_search.update_results_complete");
		}
		
		this.update_results_complete = function(content){
			this.is_updating(false);
			jQuery('#game_group_search_results').html(content);
			this.initialize_html();
		}
		
		//used to set or get whether an update is in progress. pass null to get, true or false to set
		this.is_updating = function(updating){
			if(updating == null) return this.updating;
			
			if(updating){
				this.updating = true;
				this.html_element.addClass('updating');
			} else {
				this.updating = false;
				this.html_element.removeClass('updating');
			}
		}
		
		this.initialize_html();
	}
	
	function Rotator(element, id){
		this.id = id;
		this.timeout = null;
		this.delay = 4000;
		this.element = jQuery(element);		
		
		this.init = function(){
			this.init_links();
			this.start();
		}
		
		this.images = function(){
			return this.element.find('ul.images li');;
		}
		
		this.links = function(){
			return this.element.find('ul.links li');
		}
		
		this.init_links = function(){
			var rotator = this;//pull into scope
			this.links().click(function(e){
				e.preventDefault();
				$this = jQuery(this);
				item_id = $this.prevAll().length;
				app.rotators[rotator.id].show(item_id);
			});
		}
		
		this.next = function(){
			var active_image = this.images().filter('.active');
			var next_image = active_image.next().length>0? active_image.next() : this.images().eq(0); //next or first

			var active_link = this.links().filter('.active');
			var next_link = active_link.next().length>0? active_link.next() : this.links().eq(0); //next or first

			active_image.removeClass('active');
			next_image.addClass('active');
			
			active_link.removeClass('active');
			next_link.addClass('active');
		}
		
		this.show = function(item_id){
			if(item_id > this.images().length) return false;
			this.images().removeClass('active').eq(item_id).addClass('active');
			this.links().removeClass('active').eq(item_id).addClass('active');
			this.restart_timer();
		}
		
		this.start = function(){
			this.timeout = setInterval("app.rotators["+this.id+"].next()", this.delay);
		}
		
		this.stop = function(){
			clearTimeout(this.timeout);
		}
		
		this.restart_timer = function(){
			this.stop();
			this.start();
		}
		
		this.init();
	}
	
	this.init();
}

app = new app;