//  pageload() variables ***************/

// flag for first loading of the page
var PAGE_REFRESH = true;

// main page for navigation
var PAGE = '';
// topic to navigate to on main page
var PAGE_TOPIC = '';

function pageload(hash) {
	PAGE_TOPIC = '';
	 //alert("pageload: " + hash);
	$("#ajax_loading").fadeIn();
	$("#home_button, #footer, #new_footer").fadeOut(300);
	
	scrollToTop();

	if(hash) {
		var values = hash.split("/");
		// main page
		PAGE = values[1];
		
		// for scrolling to specific page heading
		if(values[2])
			PAGE_TOPIC = values[2];
			
	} else {
		PAGE = 'home';
	}
	
	if(!PAGE_REFRESH) {
		// animate portfolio slider
		if(PAGE == 'home')
			openSlider();
		else
			squeezeSlider();	
	} else {
            
	if(PAGE == 'home')
			openSlider();
		else
			squeezeSlider();		
        }
	
	//alert("page:"+PAGE);
	
	$.ajax({
		type:'POST',
		url: "handlers/get_page.php",
		data:"page="+PAGE+"&page_topic="+PAGE_TOPIC,
		dataType:"json",
		success: function(msg){
                    if(parseInt(msg.status)==1){
                        loadContent(msg);
                        
                        //if(PAGE!='home' && PAGE!='site-map' && PAGE!='privacy-policy') { //fast fix for 'the-space'
                        if(PAGE!='home' && PAGE!='site-map' && PAGE!='privacy-policy' && PAGE!='the-space') {

                                // hide home button and reposition above active .top_nav link
                                var pos = $("#"+PAGE).position();
                                $("#home_button").fadeOut(function(){$(this).css({top:pos.top-8, left:pos.left+100}).fadeIn();});

                                // reset all .top_nav buttons except for the selected page
                                $(".top_nav:not(#"+PAGE+")").animate({ 'backgroundColor':'#333333', 'marginTop':5, height:32}, 300).removeClass("nav_active");

                                // display current nav setting if not already set
                                $("#"+PAGE).animate({ 'backgroundColor':'#00ADEE', 'marginTop':5, height:39  }, 150).addClass("nav_active"); 

                        } else {
                                // remove current nav selection as we are now back at home
                                $(".nav_active").stop().animate({ 'backgroundColor':'#333333', 'marginTop':5, height:32}, 300).removeClass("nav_active"); 
                        }

                    } else {
                            squeezeSlider();
                            $("#page_content_left").fadeOut(function(){
                                    $(this).html("<div class='page_block' style='height:140px;'><h2>Error: This Page Does Not Exist.</h2></div><div class='clear'></div>").fadeIn();
                                    $("#footer, #new_footer").fadeIn();																			
                            });
                            $("#page_content_right").fadeOut(); 
                    }
		}//,
//		error: function(a,b,c,d) {
//			alert('ajax error');	
//                        //alert(d);
//		}
	});
	
} // pageload(hash)


function loadContent(msg){
	//alert(msg.left);
	$("#page_content_left").fadeOut(800, function(){
		$("#page_content_left").html(msg.left).fadeIn(400);
		
		if(PAGE=='contact')
		{
			reloadMap();
		}
                
                 // back to top button
                if(PAGE!='home') {
                    toTop();
                    $('#toTop').css('margin','0px');
                    $('#toTop').css('margin-left','810px');
                } else {
                    $('#toTop').css('margin','9999999px');
                }
		
		$("#page_content_right").fadeOut(function(){
			$("#page_content_right").html(msg.right).fadeIn(function(){
				globalFunctions();
				$("#footer, #new_footer").fadeIn();	

				// scroll page to specific page header if one is selected
				if(PAGE_TOPIC != ''){					
//					if(PAGE=='case-studies')
//					{
//						$("div.studies").hide();
//						$('div.'+PAGE_TOPIC).fadeIn();
//					}
                                    if(PAGE!='case-studies') {
                                            var pos = $("h2[rel="+PAGE_TOPIC+"]").position();
                                            scrollToTop(pos.top-25);
                                            $("h2[rel="+PAGE_TOPIC+"]").parents('div').animate({borderTopWidth:5});
                                    }
				}
				
				
				
				// reposition home button if scrollbars are introduced or taken away
				slideHome();
				
       
				if(PAGE_REFRESH) {
					// scripts.js - preload all site images from the the image directory collection
					// pass in csv of images stored in directory.
					// after images are cached, the rest of the slideshow "Portfolio" images are loaded
					//$.preLoadImages(IMAGES_CSV, loadSlideshow);
					PAGE_REFRESH = false;
				}
				
			});  //  $("#page_content_right").fadeIn()
		});  //  $("#page_content_right").fadeOut
	});  //  $("#page_content_left").fadeOut()
	
}


function slideHome(){
	// hide home button and reposition above active .top_nav link
	if( $("#"+PAGE).is("*") ) {
		var pos = $("#"+PAGE).position();
		$("#home_button").animate({top:pos.top-8, left:pos.left+100}, 100);
	}
}

function reloadMap(){
	init_map();
	
}

// settings for page elements. called after each pageload
function globalFunctions(){
	// set hash navigation links
	$('a[rel="history"]').bind('click', historyNav);
	
	// create hash links if javascript is enabled
	$('a[rel="history"]').each(function(){
		var href = $(this).attr('href');
		if(href.indexOf('.php') != -1){
                    $(this).attr('href', '#/'+href.replace('.php', ''));
		}
	});
        
        $('.topper').click(function() {
           scrollToTop();
        });
        
        

        $(window).resize(function() {
          //$('#hero_graphic').removeAttr('width');
          $('.slider').css('width','100%');
          $('#hero_graphic').css('width','100%');
          $('#hero_slider').css('width','100%');
          $('.hero_slider').css('width','100%');
        });
	//#hero_graphic
	
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// set up rollovers images
	// give all rollover images the same name and add '-over' to allow this script to affect all images
	// eg: arrow.png, arrow-over.png
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	
	$('.rollover_image').each(function() {
	
		// rollover images
		var src = $(this).attr('src');
		var ext = src.substring(src.length-4);
		var over_src = src.replace(ext, "-over"+ext);

		// rollover image
		$(this).hover(function() {
			$(this).attr('src', over_src);
		}, function() {
			$(this).attr('src', src);
		});
		
	});
	
	$('.active_image').each(function (){
		var src = $(this).attr('src');
		var ext = src.substring(src.length-4);
		var over_src = src.replace(ext, "-click"+ext);
		$(this).mousedown(function(){
			$(this).attr('src', over_src);
		});
		$(this).mouseup(function(){
			$(this).attr('src', src);
		});		
		
	});
	

	// Second navigation links set up
	$('.second_nav').each(function(){
		$(this).click(function(){
                    
			var id = $(this).attr('id');
			var pos = $("h2[rel="+id+"]").position();
			scrollToTop(pos.top-25);
			$(".page_block").animate({borderTopWidth:0});
			$("h2[rel="+id+"]").parents('.page_block').animate({borderTopWidth:5});
                        
		});
	});
        
	
	$("a.collapsible_button").click(function (){
		$class=($(this).attr('id'));
		$this=$(this)
		if(! $('.'+$class).is(':visible') )
		{
			$("."+$class).fadeIn(function (){
				$(".collapsible").not('.'+$class).fadeOut(function (){
					var id = $this.attr('id');
					var pos = $("#page_content_right").position();
					scrollToTop(pos.top-5);
					//$(".page_block").animate({borderTopWidth:0});;
					//$("h2[rel="+id+"]").parents('.page_block').animate({borderTopWidth:5});	
				});
			});
		}
		
	});
	
	// jquery corners
	$('.custom_button_wrapper').corner('7px');
	$('.selectbox_custom').corner('7px');
	$('#footer').corner('5px');
	
	// add dotted bottom border to the bottom of page_blocks except for the last one. Same with the leadership list blocks
	if(PAGE!='case-studies')
	{
		$('.page_block').not(':last').addClass('border_bottom_dotted');
		$('.leadership_table').not(':last').addClass('border_bottom_dotted');
	}
	
	// set onclick for submit buttons
	$("#submit").click(function(){												
		$(this).parents("form").submit();
	});
        
        stButtons.locateElements(); // used for share this
        
        jQuery.fn.mailme = function() {
            var at = / at /;
            var dot = / dot /g;
            this.each( function() {
                var addr = jQuery(this).text().replace(at,"@").replace(dot,".");
                var title = jQuery(this).attr('title')
                $(this)
                    .after('<a href="mailto:'+addr+'" title="'+title+'">'+ addr +'</a>')
                    .remove();
            });
        };
        
        $('span.mailme').mailme();

}

function historyNav(){
	// set onlick event for buttons for hash navigation
	var hash = this.href;
	hash = hash.replace(/^.*#/, '');
	$.historyLoad(hash);
	return false;
}


