/* INPUT WATERMARKS
*************************************************************/
function InputWatermark(obj_ref,text){
	var self = this;
	
	self.input_text = (text != null) ? text : 'Enter text here...';
	self.obj_ref = obj_ref;
	
	if($(self.obj_ref).hasClass('required')) {
		self.input_text += ' *';
	}
	
	self.init = function(){
		if(self.obj_ref == null){ return false; }
		
		$(self.obj_ref).attr("value", self.input_text);  
		
		$(self.obj_ref).focus(function () {
		    if($(this).attr("value") == self.input_text)
		        $(this).attr("value", "");
		});
		$(self.obj_ref).blur(function () {
		    if ($(this).attr("value") == "") 
		        $(this).attr("value", self.input_text);  
		});
	}
	
	self.init();
}

function formWatermarks(){
	var self = this;
	self.init = function(){
		if($("form").length > 0) {
			$("label").each(function(){
				var formId = '#' + $(this).attr("for");
				var formLabel = 'Enter your ' + $(this).html();
				if($(formId).is("input")) {
					window["watermark"+formId] = new InputWatermark(formId,formLabel);
				}
			});
		}
	}
	
	self.init();
}

function slideShow(autoPlay) {
	var self = this;
	self.slideShowContainer = "slideshow";
	self.slideClass = "slide";
	self.slideMaskContainer = "slide-mask-container";
	self.activeSlideIndex = 0;
	self.nextButtonClass = "next";
	self.prevButtonClass = "prev";
	self.tabs = "tabs";
	self.tabsContainer = "tabs_container";
	self.tabsContainerWidth = "";
	self.tabsContainerPadding = "";
	self.interval = 7000;
	self.fadeSpeed = 700;
	self.intervalFunction = "";
	self.autoPlay = true;
	self.imageHeight = "";
	self.imageHeight = "";
	
	if(autoPlay == false || $('.slide').size() <= 1) {
		self.autoPlay = false;
	} else if(autoPlay == "") {
		self.autoPlay = true;
	}
	
	self.init = function() {
		if($("." + self.slideShowContainer).length > 0) {
			
			//Build the slideshow
			if($("." + self.slideMaskContainer).length > 0) {
				if($("." + self.slideClass).length > 0) {
					
					//Retrieve the image dimensions to size the slideshow accordingly.
					//This means that using the build_image_tag function we can specify the width and height of the slideshow.
					self.imageHeight = (parseInt($("." + self.slideShowContainer + " img").height()) > 323) ? "323px" : parseInt($("." + self.slideShowContainer + " img").height());//($("." + self.slideShowContainer + " img").height()) + "px";
					//self.imageWidth = "947px";
					self.imageWidth = ($("." + self.slideShowContainer + " img").width()) + "px";
					
					$("." + self.slideShowContainer).css("height",self.imageHeight);
					if(parseInt(self.imageWidth.replace('px','')) > 900){
						$("." + self.slideShowContainer).css("width","950px");
					} else {
						$("." + self.slideShowContainer).css("width","696px");
					}
					$("." + self.slideShowContainer).css("border-right","3px solid #FFC919");
					$("." + self.slideShowContainer).css("overflow","hidden");
					
					//Size the tabs area dynamically based on the image dimensions
					if($("." + self.tabsContainer).length > 0) {
						self.tabsContainerWidth = $("." + self.tabsContainer).css("width");
						self.tabsContainerWidth = parseInt(self.imageWidth) - parseInt(self.tabsContainerWidth);
						self.tabsContainerPadding = Math.round(self.tabsContainerWidth / 2) + "px";
						$("." + self.tabsContainer).css("paddingLeft",self.tabsContainerPadding);
						var offset = (parseInt(self.imageWidth.replace('px','')) > 900) ? 12 : 2;
						self.tabsContainerWidth = parseInt(self.imageWidth) - parseInt(self.tabsContainerPadding) - offset + "px";//Odd with the 2, but it is in here to account for the 1px yellow border
						$("." + self.tabsContainer).css("width",self.tabsContainerWidth);
					}
					
					//Size the actual slide area and its outer container dynamically based on the image dimensions
					$("." + self.slideClass).css('height', self.imageHeight);
					$("." + self.slideClass).css('width', self.imageWidth);
					$("." + self.slideClass).css('overflow','hidden');
					$("." + self.slideMaskContainer).css('height', self.imageHeight);
					
					if(parseInt(self.imageWidth.replace('px','')) > 900){
						$("." + self.slideMaskContainer).css('width', "947px");//self.imageWidth);	
					} else {
						$("." + self.slideShowContainer).css("width",self.imageWidth);
					}
					$("." + self.slideMaskContainer).css('overflow', "hidden");//self.imageHeight);
					
					//Hide the slides and fire the first one to active
					$("." + self.slideClass).hide();
					$("." + self.slideClass).eq(self.activeSlideIndex).show();
					$("." + self.slideMaskContainer).fadeIn(self.fadeSpeed, function() {
						if(self.autoPlay == true) {
							self.intervalFunction = setInterval(function() { self.loadSlide("+"); }, self.interval);
						} else {
						}
					});
				}
			}	
						
			//Setup the next and previous button functionality
			if($("." + self.nextButtonClass).length > 0) {
				$("." + self.nextButtonClass).click(function() {
					clearInterval(self.intervalFunction);
					self.loadSlide("+");
					return false;
				});
			}
			if($("." + self.prevButtonClass).length > 0) {
				$("." + self.prevButtonClass).click(function() {
					clearInterval(self.intervalFunction);
					self.loadSlide("-");
					return false;
				});
			}
			
			//Setup the tabs button functionality
			if($("." + self.tabs + " a").length > 0) {
				$("." + self.tabs + " a").click(function() {
					clearInterval(self.intervalFunction);
					self.loadSlide($(this).index());
					return false;
				});
			}
		}
	}
	
	self.loadSlide = function(action) {
		if(self.activeSlideIndex != action) {
			$("." + self.slideClass).eq(self.activeSlideIndex).fadeOut(self.fadeSpeed);
			
			if(action == "+") {
				if(self.activeSlideIndex + 1 > $("." + self.slideClass).length - 1) {
					self.activeSlideIndex = 0;
				} else {
					self.activeSlideIndex = self.activeSlideIndex + 1;
				}
			} else if(action == "-") {
				if(self.activeSlideIndex - 1 < 0) {
					self.activeSlideIndex = $("." + self.slideClass).length - 1;
				} else {
					self.activeSlideIndex = self.activeSlideIndex - 1;
				}
			} else if(isFinite(String(action))) {
				self.activeSlideIndex = action;
			}
			
			$("." + self.slideClass).eq(self.activeSlideIndex).fadeIn(self.fadeSpeed);
			if($("." + self.tabs + " a").length > 0) {
				$("." + self.tabs + " a").each(function() {
					$(this).removeClass("active");
				});
				$("." + self.tabs + " a").eq(self.activeSlideIndex).addClass("active");
			}
		}
	}	
	self.init();
}

function equalColHeights() {
	self.height = 0;
	self.highest;
	self.colClass = "col div";
	self.init = function() {
		if($("." + self.colClass).length > 0) {
			$("." + self.colClass).each(function() {
				if($(this).outerHeight() > self.height) {
					self.highest = $(this);
					self.height = self.highest.outerHeight();
				}
			});
			$("." + self.colClass).css("height",self.height + "px");
		}
	}
	self.init();
}

function completeCTA() {
	self.prependText = '<span class="left"></span>';
	self.appendText = ' >><span class="right"></span>';
	self.init = function() {
		if($(".cta").length > 0) {
			$(".cta").prepend(self.prependText);
			$(".cta").append(self.appendText);
		}
	}
	self.init();
}

function addImageBase() {
	self.init = function() {
		if($(".add_base").length > 0) {
			$(".add_base").wrap('<span class="img_base" />');
			$(".img_base").append("<span />");
		}
	}
	self.init();
}

function contact_form_tabs() {
	var self = this;
	
	self.init = function() {
		//GET URL
		var url = window.location.hash;
		var urlParts = url.split('#');
		var tab = urlParts[1];
		
		//On page load
		$(".tab_content").hide();
		$('#tabs li:first').addClass('active').show();
		$('.tab_content:first').show();
		
		if(tab == "get_quote") {
			$('#tabs li:first').removeClass('active').show();
			$('#tabs li:nth-child(2)').addClass('active').show();
		} else 	if(tab == "service-request") {
			$('#tabs li:first').removeClass('active').show();
			$('#tabs li:nth-child(3)').addClass('active').show();
		}
		
		//On click
		$('#tabs li').click(function() {
			$('#tabs li').removeClass('active');
			$(this).addClass('active');
			$('.tab_content').hide();
			
			var activeTab = $(this).find('a').attr('href');
			$(activeTab).fadeIn('slow');
			return false;
		});
		
	}
	
	self.init();
}

function applyDialog() {
	//In order to use the dialog you need to create a link containing a rel attribute that is identical to the class attribute on the dialog block
	var self = this;
	self.linkRelAttr;
	self.width = 506;//Default width for the dialog
	self.title;//Default title for the dialog
	
	
	//This function will convert any items with the class attribute beginning with dialog to a dialog modal window
	self.init = function() {
		if($('[class^=dialog]').length > 0) {
			$('[class^=dialog]').each(function() {
				if($(this).attr("width") != null) {
					self.width = parseInt($(this).attr("width"));
				}
				if($(this).attr("title") != null) {
					self.title = $(this).attr("title");
				}
				$(this).dialog({
					autoOpen: false,
					modal: true,
					resizable: false,
					draggable: false,
					position: 'center',
					closeText: 'X',
					width: self.width,
					title: self.title
				});
			});
		}
		self.applyDialogLink();
	}
	
	//This will apply the dialog click functionality to any links containing the rel attribute beginning with dialog
	self.applyDialogLink = function() {
		if($('[rel^=dialog]').length > 0) {
			$('[rel^=dialog]').click(function() {
				
				self.linkRelAttr = $(this).attr("rel");
				if($("." + self.linkRelAttr).length > 0) {
					$("." + self.linkRelAttr).dialog("open");
					return false;
				}
			});
		}
	}
	self.init();
}

function Pagination(pagination_path,load_first_page){
	var self = this;
	self.current = 1;
	self.direction = 0;
	self.totalPages = 0;

	self.init = function() {
		
		// Highlight the first page and disable the previous button
		$('#pagination li a.page:first').addClass('active_pagination');	
		self.totalPages = $('#pagination .page').length;
		
		// Bind the click events to the buttons. 
		self.binding();
		
		// Sometimes the first page will not be loaded by default, load 
		// the first page. 
		if(load_first_page) {
			self.paginate(0);
		}
	}
	
	self.binding = function() {

		// Bind the click event to all pagination buttons
		$('#pagination li a.page').unbind('click').click(function() {
		 	var activePage = parseInt(this.id);
			if(self.current == activePage)
				return true;
			else {
			  	$('#pagination li a').css({ 'color' : '#FFF' });
				self.current = activePage;
				self.paginate(0);
				return true;
			}
			return false;
		});
		
		// Bind the previous and next buttons. 
		$('#previous').unbind('click').click(function() {
			self.paginate(-1);
			return true
		});	
		
		$('#next').unbind('click').click(function() {
			self.paginate(1);
			return true;
		});
	
	}
	
	self.paginate = function(direction){
		
		//Find the activated page and test if in bounds
		activePage = self.current + direction;
		
		// Shouldn't happen if the buttons are disabled
		if(activePage < 1 || activePage > self.totalPages){
			return true;
		} 	
		
		//Start loading
		self.loading();
		
		//Remove all button highlights and disable
		$('#pagination li a.page').removeClass('active_pagination');
		
		//Update the current page
		self.current = activePage;
		self.direction = direction;
		
		//Add all the button highlights and disables
		$('#'+self.current).addClass("active_pagination");
			
		//Load the content
		$("#pagination_content").load(pagination_path + activePage, self.loading_complete());
		
	}
	
	self.loading = function() {

		// Fade out the content and add a loader image, while content is being
		// retrieved
		$("#pagination_content").fadeOut('slow');
		$('#loading').fadeIn(900, 0);
		$('#loading').html('<img src="/t/images/ajax-loader.gif" />');
	}
	
	self.loading_complete = function() {
		
		// Fade in the content
		$('#loading').fadeOut(900, 0);
		$("#pagination_content").fadeIn('slow');
	}
	
	self.init();
}


function dialog() {
	var self = this;
	
	self.init = function() {
		$('.poplight[href^=#]').click(function() {
			self.popID = $(this).attr('rel');
			self.popURL = $(this).attr('href');
			self.popWith = 500;
			self.margTop = ($('#' + self.popID).height + 80) / 2;
			self.margLeft = ((parseInt($(window).width()) / 2) - (parseInt($("#" + self.popID).width()) + 115) / 2) ; //extra for padding added
			self.fadeSpeed = 230;
			
			$('#' + self.popID)
				.fadeIn(self.fadeSpeed)
				.css({ 'width' : Number(self.popWidth) })
				.prepend('<a href="#" class="close"><img src="/t/images/dialog_close_btn.png" class="close" title="Close Window" alt="Close Window" /></a>');
		
			$('#' + self.popID).css({
				'margin-top' : -self.margTop,
				'left' : self.margLeft
			});
			
			$('body').append("<div id='fade'></div>");
			
			$('#fade').fadeIn(self.fadeSpeed);
			
			$('.close, #fade').live('click', function() {
				self.close();
				return false;
			});
			
			return false;
		});
	}
	
	self.close = function() {
		$('#fade, .popup_block').fadeOut(self.fadeSpeed, function() {
			$('#fade, .close').remove();
		});
		
		return false;
	}
	
	self.init();
}

function accordian() {
	var self = this;
	
	self.init = function() {
		//Default open/close settings
		$('.acc_container').hide();
	
		//On click
		$('.acc_trigger').click(function() {
			if($(this).next().is(':hidden')) {
				$('.acc_trigger')
					.removeClass('active')
					.next().slideUp('slow');
				
				$(this)
					.toggleClass('active')
					.next().slideDown('slow');
			}
			
			return false;
		});
	}
	
	self.init();
}

function workexperience_accordian() {
	var self = this;
	
	self.init = function() {
		
		//Default open/close settings
		if($('#visible_groups').val()=="4") {
			$("div:contains('Resume')").parent().show();
			$("h4:contains('Previous Employment Record')").parent().parent('.applyform_group').hide();
		} else {
			$("div:contains('Resume')").parent('.applyform_group').hide();
			$("h4:contains('Previous Employment Record')").parent().parent().show();	
		}
	
		//On click
		$('.coverletter_trigger').click(function() {
			$("div:contains('Resume')").parent().show();
			$("h4:contains('Previous Employment Record')").parent().parent('.applyform_group').hide();
			$("#visible_groups").val('4');
			return false;			
		});
		
		$('.workexperience_trigger').click(function() {
			$("div:contains('Resume')").parent('.applyform_group').hide();
			$("h4:contains('Previous Employment Record')").parent().parent().show();
			$("#visible_groups").val('3,2,1');
			return false;
		});
	}
	
	self.init();
}

function setRequiredFields() {
	var self = this;
	
	self.init = function() {
		var lastid = '';
		$('.required').each(function(){
			var id = $(this).attr("id");
			if(id == lastid) {
				return true;
			}
			else {
				$('label[for='+id+']').append(' *');
				lastid = id;
			}
		});
	}
	
	self.init();
}



function get_contact_locations() {
	var self = this;
	self.branchInput = "branch_email";
	self.loadInto = "locations";
	self.formContainer = "#contact_us";
	self.hiddenInput = "#branch_location";
	self.init = function() {
		if($("#" + self.branchInput).length > 0) {
			$.post('/t/scripts/get_locations.php', $(self.formContainer).serialize(), function(data) {
  				$("#" + self.branchInput).replaceWith(data);
				$("#" + self.branchInput).change(function() {
					$("#" + self.branchInput + " option:selected").each(function() {
						var current_location = $(this).text();
						$(self.hiddenInput).val(current_location);
					});
				});
				
			});
			setRequiredFields();
		}
	}
	self.init();
}



/* DOCUMENT READY FUNCTION
*************************************************************/
$(document).ready(function(){
	
	if($(".slideshow").length > 0) {
		var slideShowGo = new slideShow();
	}
	if($("#home").length > 0) {
		var equalColHeightsGo = new equalColHeights();
	}
	if($(".cta").length > 0) {
		var completeCTAGo = new completeCTA();
	}
	if($(".add_base").length > 0) {
		var addImageBaseGo = new addImageBase();
	}
	
	var tab_bars = new contact_form_tabs();
	var services_dialog = new dialog();
	var careers_accordian = new accordian(); 
	var formWatermark = new InputWatermark("#cse-search-textbox","Enter your search...");
});


