/*******************************************************************************
	Filename		: gorilla.js

	Called by		: header.php

	Created			: 29 March 2010
	Created by		: Rick Holmes
	Last Updated	: 29 March 2010 (10:38:15)

	Required files	: 

	Comments		: 
*******************************************************************************/	

$(document).ready(function() {
	GWS.init();

});

//});
var GWS = function() {
	
    /*******************************************************************************************
     	PRIVATE PROPERTIES AND METHODS
     *******************************************************************************************/

	// a little browser sniffing
//    var ie6 = ($.browser.msie && parseInt(jQuery.browser.version) < 7) ? true : false;
//    var ie7 = ($.browser.msie && parseInt(jQuery.browser.version) < 8) ? true : false;
	
	/***************************** "Constants" ******************************/

	var SITE_URL = site_url; // site_url written in header.php
	var THEME_URL = SITE_URL + '/wp-content/themes/gorilla/';
	var GRAPHICS_URL = THEME_URL + 'graphics/'
	var AJAX_URL = THEME_URL + 'ajaxfunctions/';

	var oldbrowser = false;
	var browser = {};

    /***************************** Private Properties *****************************/
    
    var pageId;
    var pageClasses; // array
    // list of dynamically loaded files for loadPlugins
    var filelist = [];
	
	// form validation data for use with jquery.validate plugin
	/* FORMAT:
	var pagerules = {
		form_id : {
			field_id :		{rule: true},
			token :			{required : true,
								remote: {
									type :	'post',
									url :	AJAX_URL+'token.php',
									data :	{
										hash : function() {
											return Cookie.read('token');
										}
									}
								}
							}	
		}
	}
	var pagemessages = {
		form_id : {
			field_id : 'Message'
		}
	}
	*/
	var pagerules = {
		'request_form' : {
			contact_name:	{required: true},
			contact_email: {required: true, email: true},
			contact_phone: {required: true, phone: true},
			ts:				{remote: {
										type : 'post',
										url : AJAX_URL + 'token.php',
										data : {
											hash : function() {
													return Cookie.read('token');
												}
											}
										}
								}
		},
		
		'contact_form' : {
			name:		{required: true},
			email:	{required: true, email: true},
			subject:	{required: true},
			message:	{required: true},
			ts:				{remote: {
										type : 'post',
										url : AJAX_URL + 'token.php',
										data : {
											hash : function() {
													return Cookie.read('token');
												}
											}
										}
								}
		}
	};
	
	var pagemessages = {
		'request_form' : {
			contact_name:	'Your name is required',
			contact_email:	'A valid email address is required',
			contact_phone: 'Your phone number is required',
			ts:			'Please enable cookies on your browser, reload the page and try again'
		},
		
		'contact_form' : {
			name:		'Your name is required',
			email:	'A valid email address is required',
			subject:	'A subject for your message is required',
			message:	'What would you like to tell us?'
		}
			
	};

	/* var pageparams = {
		'request_form' : 'getrequest',
		'contact_form' : 'contactus'
	}; */
	
	var slideshowdata = {};
	
    /***************************** Dynamically loaded items *****************************/

	// Plugins. Note: plugin_data can only uses one entry for a page, if both needed, use entry for id, which overrides class. NOTE: css loading doesn't seem to work for IE6
    /* FORMAT:
     var plugin_data = {
     mypage_id_or_class: {
	     filestoget:		[myfilepath1, myfilepath2], // put js last
	     callback:		'myfunction' // callback for last js function
     }
     };
     */
	var plugin_data;
	
	// Global functions: array of functions to fire onready for every page
    var globalfunctions = ['iePngFix']; 
    
    // Page functions, based on page id (default) and page class
    var pagefunctions = {
		// pageid	: ['function1', 'function2']
		home : ['homeSlideshow'],
		
		about : ['fixRolePosition'],
		
		'request-for-proposal' : ['placeholder', 'validateForm'],
		
		contact : ['validateForm']
		
    };
    
    /********************************* Helpers *********************************/
    
    // helper for plugin loader
    function createCallback(methodName){
    	var that = this;
        return function(){
            that[methodName]();
        };
    }
 
    // preloads regular images
    function preloadImages(src){
        $('<img>').attr('src', src);
    }
    
    // cookie functions
    var Cookie = {
        create: function(name, value, days){
            var expires;
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                expires = "; expires=" + date.toGMTString();
            }
            else {
                expires = "";
            }
            document.cookie = name + "=" + value + expires + "; path=/";
        },
        
        read: function(name){
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) === ' ') {
                    c = c.substring(1, c.length);
                }
                if (c.indexOf(nameEQ) === 0) {
                    return c.substring(nameEQ.length, c.length);
                }
            }
            return null;
        },
        
        erase: function(name){
            document.cookie = name + "= ; max-age=-1; path=/";
        },
        
        test: function(){
            // try to create a cookie
            this.create('test', 'testing');
            // then read it
            if (this.read('test') === 'testing') {
                this.erase('test');
                return true;
            }
            else {
                return false;
            }
        }
    };
        
	/***************************** Private Methods *****************************/
    

	/*******************************************************************************************
    	PUBLIC PROPERTIES AND METHODS
    *******************************************************************************************/
        

	return {
		
		// starts the ball rolling
		init: function() {
			// tag any older browsers 
			this.tagOlderBrowsers();
			// get the page id and classes
			this.getPageIdentities();
		    // load any global functions	
		    this.globalLoadFunctions();
		    // load any page-specific files and callbacks
		    this.loadPlugins();
		    // load any page-specific (non-plugin) functions
		    this.pageLoadFunctions();
						
		},
		
        /***************************** Dynamic Loaders *****************************/
        
        // global on-ready functions
        globalLoadFunctions: function(){   
            try {
                for (var i = 0; i < globalfunctions.length; i++) {
                    this[globalfunctions[i]]();
                }
            } 
            catch (ex) {
            }
        },
        
        // the plugin loader, callbacks below
        loadPlugins: function(){ 
			// rename the object
			var that = this;  
            // disable for ie lte6
            //if (ie6) 
                //return;
            var filecount, filetype, filepath, callback, i, j;
            
            // first the classes
            for (j = 0; j < pageClasses.length; j++) { 
                try {
                    // load the file(s)
                    filecount = plugin_data.pageClasses[j].filestoget.length; 
                    //callback = (plugin_data[pageClasses[j]]['callback'] == null)?  plugin_data[pageClasses[j]]['callback'] : false;
                    callback = plugin_data.pageClasses[j].callback;
                    for (i = 0; i < filecount; i++) {
                        // check filetype
                        filepath = plugin_data[pageId].filestoget[i];
                        filetype = filepath.substr(filepath.lastIndexOf('.') + 1);
                        if (filetype === 'css') {
                            // first, has it already been loaded?
                            //if (hasBeenLoaded(filepath)) 
                            if ($('link[href="'+filepath+'"]').length > 0)
                                continue;
                            // load the css file
                            $('head').append('<link rel="stylesheet" type="text/css" href="' + filepath + '" />');
                        }
                        else {
                            // load the script file, run callback on last one only
                            if (i === filecount - 1) {
                                $.getScript(filepath, function(){
                                    if (callback) that[callback]();
                                });
                            }
                            else {
                                $.getScript(filepath);
                            }
                        }
                        filelist.push(filepath);
                    }
                } 
                catch (e1) {
                    // in case it's not used
                }
            }
       
            // now do the id
           try { 
                // load the file(s)
                filecount = plugin_data[pageId].filestoget.length;	
                callback = plugin_data[pageId].callback; 
                for (i = 0; i < filecount; i++) { 
                    // check filetype
                    filepath = plugin_data[pageId].filestoget[i];
                    filetype = filepath.substr(filepath.lastIndexOf('.') + 1);
                    if (filetype === 'css') { 
                        // first, has it already been loaded?
                        if (hasBeenLoaded(filepath)) 
                            continue;
                        // load the css file
                        $('head').append('<link rel="stylesheet" type="text/css" href="' + filepath + '" />');
                    } else {
                        // load the script file, run callback on last one only
                        if (i === filecount - 1) {
                            $.getScript(filepath, function(){
                                if (callback) that[callback]();
                            });
                        }
                        else {
                            $.getScript(filepath);
                        }
                    }
                    filelist.push(filepath);
                }
            }  catch (e2) {
                // in case it's not used
            }
        },
        
        // specific page-function loader, methods below        
        pageLoadFunctions: function(){
            var f, i;
            if (pagefunctions[pageId]) {
                try {
                    f = pagefunctions[pageId];
                    if (f.length > 1) {
                        for (i = 0; i < f.length; i++) {
                            this[f[i]]();
                        }
                    }
                    else {
                        this[f]();
                    }
                } 
                catch (e3) {
                }
            } else {             	
                var count = pageClasses ? pageClasses.length : 0;
                for (i = 0; i < count; i++) {
                    try {
                        var className = pageClasses[i];
                        f = pagefunctions[className];
                        if (f.length > 1) {
                            for (var j = 0; j < f.length; j++) {
                                this[f[j]]();
                            }
                        }
                        else {
                            this[f]();
                        }
                    } 
                    catch (e4) {
                    }
                }
            }
        },
        
        /***************************** Global Helpers *****************************/
        
        // put the page id and page classes into "globals" for access whenever needed
        getPageIdentities: function(){ 
            pageId = $(document.body).attr('id');
            var pageClass = $(document.body).attr('class');
            pageClasses = pageClass.split(' ');
        },

		// input placeholders, add as global
		placeholder: function() { 
			$(':text').each(function(){
				// quit if there's support for html5 placeholder
				//if ($this[0] && 'placeholder' in document.createElement('input')) return;
				
				if ($(this).val() == '') { 
					$(this).val($(this).attr('placeholder'));
				}	
				
				// set the attribute in the data() cache
				$(this).data('placeholder', $(this).attr('placeholder'));
				
			}).live('focusin', function(){
				if ($(this).val() === $(this).data('placeholder')) {
					$(this).val('');
				}
			}).live('focusout', function(){
				if ($(this).val() === '') {
					$(this).val($(this).data('placeholder'));
				}
			});
		},

	tagOlderBrowsers: function() {
		var version;
		// look for FF < 3.5, O < 10.5
		var bv = jQuery.browser.version; //lert(navigator.appVersion);
		var ua = navigator.userAgent; //alert(navigator.userAgent);
		if ($.browser.mozilla) { //alert(ua);
			version = ua.slice(ua.indexOf('Firefox')); 
			version = version.slice(version.indexOf('/')+1);
			version = version.replace('.', ''); 
			if (version < 35) {
				$(document.body).addClass('oldFirefox');
			}

		} else if ($.browser.opera) {
			version = ua.slice(ua.indexOf('Version'));
			version = version.slice(version.indexOf('/')+1);
			if (version < 10.5) {
				$(document.body).addClass('oldOpera');
			}
		} else if ($.browser.msie) {
			version = jQuery.browser.version; 
			if (version < 8) {
				$(document.body).addClass('oldIE');
			}	
		} else if ($.browser.webkit) {
			// everything should work here
		}
		/* var browser = "BROWSER INFORMATION:\n";
		for (var propname in navigator) {
			browser += propname + ': ' + navigator[propname] + "\n"; 
		}
		alert(browser); */
	},
		        
        /***************************** Plugin Callbacks *****************************/
        
        // when you don't need one
        dummy: function(){
            // do nothing
        },
               
        /***************************** On-ready Functions, global *****************************/

		iePngFix: function() { 
			//$('#sidegraphic img').supersleight({shim: GRAPHICS_URL+'clear.gif'});
			//$('.wp-page').supersleight({shim: GRAPHICS_URL+'clear.gif'});
			$('h1').supersleight({shim: GRAPHICS_URL+'clear.gif'});
			$('h2').supersleight({shim: GRAPHICS_URL+'clear.gif'});
			//$('#sociallinks img').supersleight({shim: GRAPHICS_URL+'clear.gif'});
			//$('#slideshow dt').supersleight({shim: GRAPHICS_URL+'clear.gif'});
			//$('#mainnav a').supersleight({shim: GRAPHICS_URL+'clear.gif'});
			$('.actionlinks li').supersleight({shim: GRAPHICS_URL+'clear.gif'});
			//$('#sidebar h3').supersleight({shim: GRAPHICS_URL+'clear.gif'});
			$('#portfolio .post-content li').supersleight({shim: GRAPHICS_URL+'clear.gif'});
			$('.submitbutton').supersleight({shim: GRAPHICS_URL+'clear.gif'});
			$('.website-link').supersleight({shim: GRAPHICS_URL+'clear.gif'});
		},        
 		   
        /***************************** On-ready Functions, specific pages *****************************/
			
		// client-side validation for forms, requires jquery.validate.js to be loaded, either dynamically or regular
		validateForm: function() { 
			
			// get the token for the secure form
			$.get(AJAX_URL+'token.php', function(txt) {
				$('form.secure').append('<input type="hidden" name="ts" id="ts" value="'+txt+'" />');
			});
			 			
			$('form').each(function(){ 
				formId = $(this).attr('id');
				$('#' + formId).validate({
					//debug:	true,
					errorContainer:		'#formerrors', // the div
					errorLabelContainer: '#formerrors ul', // the ul				
					errorElement:			'li', // the error
					highlight: 				function(element, errorClass) {
											     $(element.form).find("label[for=" + element.id + "] span").addClass(errorClass);
											  },
					unhighlight:			function(element, errorClass) {
											     $(element.form).find("label[for=" + element.id + "] span").removeClass(errorClass);
											  },
											
					invalidHandler:		function(){
													$('#formerrors').css({
														display: 'block'
													});
													
													$('html').animate({
														scrollTop:0}, '1000', function(){
															$('#formerrors').animate({														
																top: 200
														}, 500);
													});
														
												},
					submitHandler:			function(form){
												/* var mid;
												switch(formId) {
													case 'request_form':
														mid = '#success-message';
													break;
												} */
												var bodyheight = $('body').height();
												
												var ajaxoptions = {
													url: 		AJAX_URL + 'ajaxmail.php',
													type:		'POST',
													success:	function(statusText) { 
																	if (statusText === 'ok') {
																		$('#success-message').css('display', 'block');
																		$('html').animate({
																			scrollTop:0}, '1000', function(){
																				$('#success-message').animate({														
																					top: 200
																			}, 500);
																		});	
																	}	
																},
													resetForm:		true
												};
												$(form).ajaxSubmit(ajaxoptions);
												
												$('#success-message' + ' a.close').click(function(){ 
													$('#success-message').fadeOut(function(){$('#success-message').css({'top': '-350px', 'display': 'none'});}, 
														function() {location.href = SITE_URL; }
													);
													 
													return false;
												});												
											},
					rules: 					pagerules[formId],
					messages:				pagemessages[formId]
				});
			});
			// bind the close event
			$('#formerrors a.close').click(function(){ 
				$('#formerrors').fadeOut(function(){$('#formerrors').css({'top': '-350px', 'display': 'none'});});
				return false;
			});
		},
		
		// the slideshow for the homepage
		homeSlideshow: function() { //console.log('in function');
			// get the slideshow data onload
			$.ajax({
				url: AJAX_URL + 'homeSlideshow.php',
				data: 'category=5',
				dataType: 'json',
				success: function(data){
					for (var item in slideshowdata) {
						preloadImages(item.image[0]);
					}
					slideshowdata = data;	
				}
			});
			$('.ss_nav a').click(function(){ //console.log('clicked');
				// show 'active'
				$('.ss_nav li.active').removeClass('active');
				$(this).parent('li').addClass('active');
				// get the post id from the <img> id
				var pid = $(this).children('img').attr('id'); 
				pid = pid.slice(6); 
				
				// do the animation and swap the data
				$('#slideshow .ss_top').animate({'margin-left': '-900px'}, 500, 'linear', function(){
					$('p.excerpt').html(slideshowdata[pid].excerpt);
					$('p.cite').html(slideshowdata[pid].cite);
					var img = '<img src="' + slideshowdata[pid].image[0] + '" alt="" width="' + slideshowdata[pid].image[1] + '" height="' + slideshowdata[pid].image[2] + '" />';
					//$('#slideshow dd a').html(slideshowdata[pid].image);
					$('#slideshow dd a.main').html(img);
					
					$(this).animate({'margin-left': '0'}, 500, 'linear');
				});
				$('#slideshow dd a').attr('href', slideshowdata[pid].url);
				return false;
			});
			/* $('.ss_nav a').click(function(){
				// show "active"
				$('.ss_nav li.active').removeClass('active');
				$(this).parent('li').addClass('active');
				// get the post id from the <img> id
				var pid = $(this).children('img').attr('id'); 
				pid = pid.slice(6); 
				$.ajax({
					url: AJAX_URL + 'homeSlideshow.php',
					data: 'pid=' + pid,
					dataType: 'json',
					success: function(data){ */ 		
						/* $('#slideshow div.ss_blockquote').fadeOut(function(){							
							$('p.excerpt').html(data.excerpt);
							$('p.cite').html(data.cite);
							$(this).fadeIn();	
						});
						$('#slideshow a.main').fadeOut('fast', function(){
							$(this).html(data.image);															
							$(this).fadeIn('fast');
						})
						$('#slideshow dd a').attr('href', data.url); */
						/* $('#slideshow .ss_top').animate({
							marginLeft: '900px'
						}, slow); */
						/* $('#slideshow .ss_top').animate({'margin-left':'-900px'}, 500, 'linear', function(){
							$('p.excerpt').html(data.excerpt);
							$('p.cite').html(data.cite);
							$('#slideshow .ss_top a').html(data.image);
							$('#slideshow dd a').attr('href', data.url);
							$(this).animate({'margin-left': '0'}, 500, 'linear');
						});	
					}
				});
				
				return false;
			}); */
		},
		
		// fix the "role" position, it's rotated with css, but top != top
		fixRolePosition: function() { 
			setTimeout(function() {
				$('p.role span').each(function(){
					var spanwidth = $(this).width();
					$(this).parent('p').css({top: (spanwidth + 39)+'px'});
				});
			}, 50);	
		}

};	
}();

