//************************************************************************************************************//
//												CONFIG
//************************************************************************************************************//

var preload_basepath = "images/";

var expand_rollover = "&nbsp;&nbsp;<span class=\"plusminusrollover\">+ EXPAND</span>";
var collapse_rollover = "&nbsp;&nbsp;<span class=\"plusminusrollover\">- COLLAPSE</span>";

//************************************************************************************************************//
//												THE BASICS
//************************************************************************************************************//

// Sometimes I still like this instead of jQuery, as it returns an array object instead of a jquery object.
function getArrayByClass(tag_name,requested_class) {
	var dest_array = new Array();
	var all_elements_w_class = document.getElementsByTagName(tag_name);
	var obj_counter = 0;
	for (i=0; i<all_elements_w_class.length; i++) {
		var this_elements_class = all_elements_w_class[i].getAttribute("class");
		if (this_elements_class == requested_class) {
			dest_array[obj_counter] = all_elements_w_class[i];
			obj_counter++;
		}
	}
	return dest_array;
}
 
// Easy jQuery driven rollover init script. Not mine...
function initRollovers() {
	jQuery('.rollover').hover(function() {
        var currentImg = $(this).attr('src');
        
        // Adding an IF statement so current page image is not affected by rollover..
        if (currentImg.indexOf('_over') == -1) {
	        $(this).attr('src', $(this).attr('hover'));
	        $(this).attr('hover', currentImg);
	        $(this).attr('current','no');
	    }
	    // Add a CURRENT attribute so mouseouts don't remove image of current page.
	    else {
	    	$this.attr('current','current');
	    }
    }, function() {
    	var current = $(this).attr('current');
    	
        if (current != 'yes') {
	        var currentImg = $(this).attr('src');
	        $(this).attr('src', $(this).attr('hover'));
	        $(this).attr('hover', currentImg);
	    }
    });
}

// Browser finder - could add on to this over time...
function getBrowser() {
	var browser;
	
	// Do mobile matching first.
	if (navigator.userAgent.match(/iphone/i)) {
		browser = "iphone";
	}
	else if (navigator.userAgent.match(/ipad/i)) {
		browser = "ipad";
	}
	else if (navigator.userAgent.match(/ipod/i)) {
		browser = "ipod";
	}
	else {
		if (navigator.userAgent.match(/chrome/i)) {
			browser = "chrome";
		}
		else if (navigator.userAgent.match(/safari/i) && !(navigator.userAgent.match(/chrome/))) {
			browser = "safari";
		}
		else if (navigator.userAgent.match(/firefox/i)) {
			browser = "firefox";
		}
		else if (navigator.userAgent.match(/opera/i)) {
			browser = "opera";
		}
		else if (navigator.userAgent.match(/MSIE/i)) {
			browser = "ie";
		}
	}
	return browser;
}

// Returns exponential sloping values instead of linear - use w/ setInterval().
function easeInOut(minValue,maxValue,totalSteps,actualStep,powr) { 
    var delta = maxValue - minValue; 
    var stepp = minValue+(Math.pow(((1 / totalSteps) * actualStep), powr) * delta); 
    return Math.ceil(stepp) 
}

// Preload image script...
function preloadImages(media_url) {
	var image_array = new Array();
	for (i=0; i<preload_array.length; i++) {
		image_array[i] = new Image;
		image_array[i].src = media_url + preload_basepath + preload_array[i];
	}
}

// Create an IMG table with absolute divs. Create a global array with img name variations for this to work.
function divTable(img_array,x_inc,y_inc,cols) {
	var html_string = "";
	var counter = 1;
	var x_increment = x_inc;
	var y_increment = y_inc
	var x_pos = 0;
	var y_pos = 0;
	
	for (i=0; i<img_array.length; i++) {
		
		html_string = html_string + ("<div id='" + img_array[i] + "' style='position:absolute;top:" + y_pos + "px;left:" + x_pos + "px;' class='div_table'><a class='slideshow' href='Media/almeria_" + img_array[i] + "_large.jpg' rel='group1'><img src='Media/almeria_" + img_array[i] + "_small.jpg' /></a></div>");
		
		if (counter <= cols - 1) {
			x_pos = x_pos + x_increment;
			counter++;
		}
		else {
			counter = 1;
			x_pos = 0;
			y_pos += y_increment;
		}
	}
	document.getElementById("img_container").innerHTML = html_string;	
}

// jQuery based Coda-style rising fade-out.
function codaExit(id,anim_time) {
	jQuery("#" + id).animate({'top' : '-=10px','opacity' : '0.0'},anim_time);
}

//************************************************************************************************************//
//												INITIALIZATION SECTION
//************************************************************************************************************//

// Make sure content bg is the same width/height as content.
function initContentBackground() {
	w = jQuery('#content').width();
	h = jQuery('#content').height();
	
	jQuery('#contentbg').css('height',h + 'px');
	jQuery('#main').css('height',(h + 500) + 'px');
}

// Simple function to init dropdown menu - grabs everything with .dropdown class...
function initDropDowns() {
	jQuery('.dropdown').each(function () {
		$(this).parent().eq(0).hover(function () {
			$('.dropdown:eq(0)',this).slideDown(100);
		}, function () {
			$('.dropdown:eq(0)',this).fadeOut(200);
		});
	});
}

// Address individual browser styling/layout problems.
function fixBrowserStuff() {
	var browser = getBrowser();
	if (browser == 'opera') {
		jQuery('.paginationleftedge').css('top','-3px');
		jQuery('.paginationrightedge').css('top','-3px');
	}
	else if (browser == 'chrome') {
		jQuery('.paginationleftedge').css('top','-1px');
		jQuery('.paginationrightedge').css('top','-1px');
	}
	else if (browser == 'safari') {
		jQuery('.paginationleftedge').css('top','-1px');
		jQuery('.paginationrightedge').css('top','-1px');
	}
	
	// Doing this in django now - deactivated in js.
	/*
var ie_version = getInternetExplorerVersion();
	if (ie_version != -1) {
		window.location = '/ieredirect/' + ie_version + '/';
	}
*/
}

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

// Determine if browser is iOS, and if so activate the iOS CSS stylesheet.
function initFonts() {
	
	var browser = getBrowser();
	
	if (browser == 'ipad' || browser == 'ipod' || browser == 'iphone') {
		setActiveStyleSheet('ios');
	}
	else if (browser == 'ie') {
		setActiveStyleSheet('ie');
	}
	else {
		setActiveStyleSheet('main');
	}
}

// Self explanatory - "title" refers to title attribute in stylesheet links.
function setActiveStyleSheet(title) {
	var i, a, main;
	
	for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
	
		if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
			a.disabled = true;
			if(a.getAttribute("title") == title) a.disabled = false;
		}
	}
}

// Sets up fancybox effect on any href with designated class.
function setupZoom() {
	jQuery("a.slideshow").fancybox();
}

// iPhoto-esque scrollover flipthru effect for photo galleries. Works presently w/ each photo in its own div.
function initScrollover() {
	// Loop thru each gallery on page and send to delegate function for initialization.
	jQuery('.mediagallery').each(function() {
		// Gather info about this gallery.
		gallery = jQuery(this);
		img_divs = gallery.find('.galleryphoto');
		count = img_divs.size();
		
		// Send data to function delegate for each gallery.
		galleryScrolloverDelegate(gallery,img_divs,count);
	})
}

function galleryScrolloverDelegate(gallery,img_divs,count) {
	img_divs.each(function(index) {
		// Find width of mouse slice(in pixels) before incrementing images.
		img_div = jQuery(this);
		width = img_div.find('img').width()
		// Hide all but the first image div.
		if (index != 0) {
			img_div.css('visibility','hidden')
		}
		// When mouse moves over gallery, gather mouse X position.
		img_div.mousemove(function(evt) {
			photoScrolloverDelegate(evt,img_divs,width,count);
		})
		gallery.mouseout(function() {
			img_divs.eq(0).css('visibility','visible');
		})
	})
}

function photoScrolloverDelegate(evt,img_divs,width,count) {
	slice_width = width/count;
	
	position = evt.layerX;
	slice = Math.floor(position/slice_width);
	for (i=0; i<count; i++) {
		if (i == slice) {
			img_divs.eq(i).css('visibility','visible');
		}
		else {
			img_divs.eq(i).css('visibility','hidden');
		}
	}
}

// Function to init Q & A style content text to be show/hide - able.
function initAccordionContent() {
	jQuery('.faqquestion').click(function() {
		
		// Grab the question number and generate appropriate answer id string.
		var question = jQuery(this).attr('id');
		var question_num = question.substr(8,question.length)
		var answer = "answer" + question_num;
		
		// Adding my own VIEWSTATE attribute here just to keep things clear and in the open.
		var view_state = jQuery("#" + answer).attr('viewstate');
		if (view_state == 'shown') {
			jQuery("#" + answer).css('display','none').attr('viewstate','hidden');
		}
		else {
			jQuery("#" + answer).css('display','block').attr('viewstate','shown');
		}
	})
}

// Function to init +/- expand/collapse functionality.
function initPlusMinusLinks() {
	jQuery('div').each(function() {
		// Check for custom attribute "plusminus" in each div - if set to "on", add expand/collapse functionality
		var plus_minus = jQuery(this).attr('plusminus');
		if ( plus_minus == 'on') {
			var obj = jQuery(this);
			div_class = obj.attr('class');
			
			// If this is the multimedia page...
			if (div_class == 'stampfixed') {
			
				obj.find('a').each(function() {
			
					link_obj = jQuery(this);
					if (link_obj.attr('plusminus') != 'ignore') {
						// ADD MM +/- TEXT TO DIV:
						var orig_text = link_obj.html();
						link_obj.html(orig_text + expand_rollover);
						// ADD MM ONCLICK FUNCTIONALITY:
						link_obj.click(function() {
							div_obj = jQuery(this).parent().parent();
							plusMinusToggleContent(div_obj,'click');
							return false;
						});
					}
				})
			}
			// If this is faq/links/contact etc - non-modded version.
			else {
				// ADD +/- TEXT TO DIV:
				var orig_text = obj.find('a').first().html();
				obj.find('a').first().html(orig_text + expand_rollover);
				
				// ADD ONCLICK FUNCTIONALITY:
				obj.click(function() {
					plusMinusToggleContent(jQuery(this),'click');
					return false;
				});
			}
			
			// ADD ROLLOVER FUNCTIONALITY:			
			obj.hover(function() {
				showPlusMinus(obj);
			},function() {
				hidePlusMinus(obj);
			});
		}
	});
	
	// Auto-expand any sub-menu category that is selected. From django "menu_category" context variable.
	if (category != "") {
		if (category == 'all') {
			// This doesn't work in MM cause of my dirty hack - should work elsewhere is we need it.
			// plusMinusActivateAll()
		}
		else {
			obj = jQuery('#' + category);
			plusMinusToggleContent(obj);
		}
	}
}


var fixed_elements = {};
fixed_elements['contentheader'] = 0;


// Keeps all designated elements fixed in window. NOT IS USE - TOO CHOPPY!
function initFixedElements() {
	jQuery(window).scroll(function() {
		var scroll_pos = jQuery(window).scrollTop();
		for (id in fixed_elements) {
			var new_elem_pos = fixed_elements[id] + scroll_pos;
			jQuery('#' + id).css('top',new_elem_pos);
		}
	})
} 


// Iframes in Chrome don't respond to z-index attributes - this fixes it.
function fixChromeOverlayBug() {
	jQuery("iframe").each( function() {
		var ifr_source = $(this).attr('src');
		var wmode = "wmode=transparent";
		if (ifr_source.indexOf('?') != -1) {
			$(this).attr('src',ifr_source + '&' + wmode);
		}
    	else {
    		$(this).attr('src',ifr_source + '?' + wmode);
    	}
	});
}


//************************************************************************************************************//
//												ACTIONS SECTION! YEAH!!
//************************************************************************************************************//

// Opens/closes content details for each +/- assigned category. 
function plusMinusToggleContent(div_obj,evt) {
	/* var div_obj = jQuery("#" + id); */
	var view_state = div_obj.attr('viewstate');
	
	if (view_state == 'shown') {
		div_obj.attr('viewstate','hidden')
		div_obj.next().each(function() {
			jQuery(this).fadeTo(150,0).slideUp(300);
		});
		plusMinusToggle(div_obj,evt);
	}
	else {
		div_obj.attr('viewstate','shown');
		div_obj.next().each(function() {
			jQuery(this).css('opacity','1').slideDown(300);
		});
		plusMinusToggle(div_obj,evt);
	}
}

// Delegate function to turn on expand/collapse rollover.
function plusMinusToggle(obj,evt) {
	var rollover_text = getPlusMinusRollover(obj);
	obj.find('span.plusminusrollover').html(rollover_text);
}

function showPlusMinus(obj) {
	obj.find('span.plusminusrollover').css('opacity','1.0');
}

function hidePlusMinus(obj) {
	obj.find('span.plusminusrollover').css('opacity','0.7');
}

// Determines whether rollover should be expand or collapse at any given time.
function getPlusMinusRollover(obj) {
	var state = obj.attr('viewstate');
	if (state == 'shown') {
		var rollover_html = '- COLLAPSE';
	}
	else {
		var rollover_html = '+ EXPAND';
	}
	
	return rollover_html;
}

// Expands/contracts all plusminus elements.
function plusMinusActivateAll() {
	jQuery('div').each(function() {
		obj = jQuery(this);
		// Find all plusminus divs.
		if (obj.attr('plusminus')) {
			// auto-expand upon page load.
			plusMinusToggleContent(obj);
		}
	})
}

// Classy way to remove messages/errors after they are shown in main div.
function clearMessages(secs) {
	var delay = secs * 1000;
	
	jQuery('.message').each(function() {
		jQuery(this).delay(delay).fadeTo(500,0).slideUp(500);
	});
	jQuery('.error_message').each(function() {
		jQuery(this).delay(delay).fadeTo(500,0).slideUp(500);
	});
}

