//Global status variables
ANIMATING = false;
ANIMATEALL = false;
LOAD_TIME_PASSED = false;
PAGE_LOADED = false;
DEFAULT_SIZE = true;
EXTRA = '';
VIEWED_IMAGE = new Frame("#imageArea0", 0);
HIDDEN_IMAGE = new Frame("#imageArea1", 1);
OLD_DOCUMENT_HEIGHT = 0;
CURRENT_IMAGE = 0;
TOP_HOME = 'blog';
SUB_HOME = 'all';
TOP_LEVEL = TOP_HOME;
SUB_LEVEL = SUB_HOME;
URL = window.location.href;
LOADING_SECTION = false;
CUR_LOADING_SECTION_ANI = false;
CURRENTLY_VIEWED_PROOFS = 0;
SHOWING_PROOF_PREVIEW = false;
BROWSING_TYPE = 'raw';
copyright_front = "<span style='padding: 5px;'>";
raw_copyright = "These are unedited proofs and not copywritten for online use. All Jessi Jefferson images must be authorized for online sharing. Posting unedited images violates copyright law. Please add photos to your edit queue to receive your web and print ready versions of all images. Thank you.";
edited_copyright = "Above is your edit queue as well as your edited images. Your edited images are outlined in a thick border, images in the queue have the normal small border."
downloads_copyright = "Above are the archives you chose to create.  You may share the archive links with your family, friends, etc...";
copyright_back = "</span>";
ldiv = 330;
pdiv = 380;
go_to_a_post = '';
SETNAME = '';
ARCHIVE_FINISHED = true;
LISTOFCURRENTIMAGEIDS = [];
LISTOFCURRENTIMAGESTOZIP = [];
LISTOFCURRENTIMAGESTOZIP2 = [];
LISTOFIMAGEIDSLEFT = [];
QUESTION_ANSWERS = [];
CONTACT_INFO = [];

function isInt(x) {
	var y=parseInt(x);
	if (isNaN(y)) return false;
	return x==y && x.toString()==y.toString();
}

function updateContact() {
	var toeval = '{';
	var count = 0;
	$(".info").each(function () {
		if (count != 0) {
			toeval += ', ';
		}
		toeval += "'" + $(this).attr('id') + "': '" + $(this).val() + "'";
		count += 1;
	});
	toeval += '}';
	CONTACT_INFO = eval("(" + toeval + ")");
	$.post("php/personal.php", {
	      'func': 'info',
	      'd': CONTACT_INFO
	    }, function(msg){
	    	alert(msg);
	    });
}

function updateQuestions() {
	$(".question_boxes").each(function () {
		var id = $(this).attr('id').split('_');
		QUESTION_ANSWERS[id[1]] = $(this).val();
	});
	$.post("php/personal.php", {
	      'func': 'questions',
	      'd': QUESTION_ANSWERS
	    }, function(msg){
	    	alert(msg);
	    });
}

function questionnaireShow() {
	$("#questions").show();
	$("#contactinfo").hide();
	$("#contact_btn").attr("src", "php/mitem.php?name=contact info&t=t&e=.jpg");
	$("#contact_btn").attr("onmouseout", "this.src='php/mitem.php?name=contact info&t=t&e=.jpg'");
    $("#contact_btn").attr("onmouseover", "this.src='php/mitem.php?name=contact info&t=lb&e=.jpg'");
    $("#q_btn").attr("src", "php/mitem.php?name=questionnaire&t=w&e=.jpg");
    $("#q_btn").attr("onmouseout", "");
    $("#q_btn").attr("onmouseover", "");
    
}

function contactInfoShow() {
	$("#contactinfo").show();
	$("#questions").hide();
	$("#contact_btn").attr("src", "php/mitem.php?name=contact info&t=w&e=.jpg");
    $("#contact_btn").attr("onmouseout", "");
    $("#contact_btn").attr("onmouseover", "");
    $("#q_btn").attr("src", "php/mitem.php?name=questionnaire&t=t&e=.jpg");
    $("#q_btn").attr("onmouseout", "this.src='php/mitem.php?name=questionnaire&t=t&e=.jpg'");
    $("#q_btn").attr("onmouseover", "this.src='php/mitem.php?name=questionnaire&t=lb&e=.jpg'");
}

function downloadsPreview() {
	$("#downloadables").css("display", "block");
	$("#cat_and_location").hide();
	$("#proofs").hide();
	$("#nav_area").hide();
	BROWSING_TYPE = 'downloads';
	if (ARCHIVE_FINISHED == true) {
		$("#download_title").html(' ');
	}
	$("#downloads").attr("src", "php/mitem.php?name=downloads&t=w&e=.jpg");
    $("#downloads").attr("onmouseout", "");
    $("#downloads").attr("onmouseover", "");
    $("#raw").attr("src", "php/mitem.php?name=raw&t=t&e=.jpg");
    $("#raw").attr("onmouseout", "this.src='php/mitem.php?name=raw&t=t&e=.jpg'");
    $("#raw").attr("onmouseover", "this.src='php/mitem.php?name=raw&t=lb&e=.jpg'");
    $("#edited").attr("src", "php/mitem.php?name=edited&t=t&e=.jpg");
    $("#edited").attr("onmouseout", "this.src='php/mitem.php?name=edited&t=t&e=.jpg'");
    $("#edited").attr("onmouseover", "this.src='php/mitem.php?name=edited&t=lb&e=.jpg'");
    $("#copyright").html(copyright_front + downloads_copyright + copyright_back);
}

function editedPreview() {
    CURRENTLY_VIEWED_PROOFS = 0;
    BROWSING_TYPE = 'edited';
    $.post("php/proofing.php", {
      'func': 'browse',
      'type': BROWSING_TYPE,
      'set_name': SETNAME,
      'location': CURRENTLY_VIEWED_PROOFS
    }, function(msg){
    	$("#downloadables").css("display", "none");
    	$("#cat_and_location").show();
    	$("#proofs").show();
    	$("#nav_area").show();
    	if (ARCHIVE_FINISHED == true) {
    		$("#download_title").html('<a onclick="create_downloadables()" style="cursor: pointer;">Create Selected Set\'s Downloadable Archives</a>');
    	}
       $("#edited").attr("src", "php/mitem.php?name=edited&t=w&e=.jpg");
       $("#edited").attr("onmouseout", "");
       $("#edited").attr("onmouseover", "");
       $("#raw").attr("src", "php/mitem.php?name=raw&t=t&e=.jpg");
       $("#raw").attr("onmouseout", "this.src='php/mitem.php?name=raw&t=t&e=.jpg'");
       $("#raw").attr("onmouseover", "this.src='php/mitem.php?name=raw&t=lb&e=.jpg'");
       $("#downloads").attr("src", "php/mitem.php?name=downloads&t=t&e=.jpg");
       $("#downloads").attr("onmouseout", "this.src='php/mitem.php?name=downloads&t=t&e=.jpg'");
       $("#downloads").attr("onmouseover", "this.src='php/mitem.php?name=downloads&t=lb&e=.jpg'");
       $("#proof_location").val(CURRENTLY_VIEWED_PROOFS);
       $("#proof_to").html(CURRENTLY_VIEWED_PROOFS + 12);
       $("#proofs").html(msg);
       $("#copyright").html(copyright_front + edited_copyright + copyright_back);
    });
    getidsofsetandtype();
}

function showWeddings() {
       $("#Weddings_image").attr("src", "php/mitem.php?name=Weddings&t=w&e=.jpg");
       $("#Weddings_image").attr("onmouseout", "");
       $("#Weddings_image").attr("onmouseover", "");
       $("#portraits_image").attr("src", "php/mitem.php?name=Portraits&t=t&e=.jpg");
       $("#portraits_image").attr("onmouseout", "this.src='php/mitem.php?name=Portraits&t=t&e=.jpg'");
       $("#portraits_image").attr("onmouseover", "this.src='php/mitem.php?name=Portraits&t=lb&e=.jpg'");
       $("#portraits").hide();
       $("#weddings").show();
}

function showPortraits() {
       $("#leftGrad").height($(window).height() - 50 + "px");
       $("#rightGrad").height($(window).height() - 50 + "px");
       $("#portraits_image").attr("src", "php/mitem.php?name=Portraits&t=w&e=.jpg");
       $("#portraits_image").attr("onmouseout", "");
       $("#portraits_image").attr("onmouseover", "");
       $("#Weddings_image").attr("src", "php/mitem.php?name=Weddings&t=t&e=.jpg");
       $("#Weddings_image").attr("onmouseout", "this.src='php/mitem.php?name=Weddings&t=t&e=.jpg'");
       $("#Weddings_image").attr("onmouseover", "this.src='php/mitem.php?name=Weddings&t=lb&e=.jpg'");
       $("#portraits").show();
       $("#weddings").hide();
}


function rawPreview() {
    CURRENTLY_VIEWED_PROOFS = 0;
    BROWSING_TYPE = 'raw';
    $.post("php/proofing.php", {
      'func': 'browse',
      'type': BROWSING_TYPE,
      'set_name': SETNAME,
      'location': CURRENTLY_VIEWED_PROOFS
    }, function(msg){
    	$("#downloadables").css("display", "none");
    	$("#cat_and_location").show();
    	$("#proofs").show();
    	$("#nav_area").show();
    	if (ARCHIVE_FINISHED == true) {
    		$("#download_title").html('<a onclick="create_downloadables()" style="cursor: pointer;">Create Selected Set\'s Downloadable Archives</a>');
    	}
       $("#raw").attr("src", "php/mitem.php?name=raw&t=w&e=.jpg");
       $("#raw").attr("onmouseout", "");
       $("#raw").attr("onmouseover", "");
       $("#edited").attr("src", "php/mitem.php?name=edited&t=t&e=.jpg");
       $("#edited").attr("onmouseout", "this.src='php/mitem.php?name=edited&t=t&e=.jpg'");
       $("#edited").attr("onmouseover", "this.src='php/mitem.php?name=edited&t=lb&e=.jpg'");
       $("#downloads").attr("src", "php/mitem.php?name=downloads&t=t&e=.jpg");
       $("#downloads").attr("onmouseout", "this.src='php/mitem.php?name=downloads&t=t&e=.jpg'");
       $("#downloads").attr("onmouseover", "this.src='php/mitem.php?name=downloads&t=lb&e=.jpg'");
       $("#proof_location").val(CURRENTLY_VIEWED_PROOFS);
       $("#proof_to").html(CURRENTLY_VIEWED_PROOFS + 12);
       $("#proofs").html(msg);
       $("#copyright").html(copyright_front + raw_copyright + copyright_back);
    });
    getidsofsetandtype();
}

function updateImage(id) {
    var tags = $("#tags").val();
    var edit = $("#edit").val();
    var impact = $("#impact").val();
    var notes = $("#notes").val();
    $.post("php/proofing.php", {
      'func': 'update',
      'type': 'image',
      'tags': tags,
      'notes': notes,
      'edit': edit,
      'impact': impact,
      'id': id
    }, function(msg){
       if (msg != '') {
       	alert(msg);
       }
       $("#post").slideUp(function(){
           $("#leftGrad").height($(window).height() - 50 + "px");
           $("#rightGrad").height($(window).height() - 50 + "px");
       });
       SHOWING_PROOF_PREVIEW = false;
    });
    
}

function showLarge(id) {
    if (SHOWING_PROOF_PREVIEW == true) {
        update = confirm("Do you wish to continue? You will lose any changes to the current image object.")
    } else {
        update = true;
    }
    SHOWING_PROOF_PREVIEW = true;
    if (update) {
        $.post("php/proofing.php", {
            'func': 'detail',
            'id': id
        }, function(msg){
            $("#post").html(msg);
            $("#post").slideDown();
            $(".fancy").fancybox();
        });
    }
}

function RorE() {
	$.post("php/proofing.php", {
	      'func': 'browse',
	      'type': BROWSING_TYPE,
	      'set_name': SETNAME,
	      'location': CURRENTLY_VIEWED_PROOFS
	}, function(msg){
	       $("#proof_location").val(CURRENTLY_VIEWED_PROOFS);
	       $("#proof_to").html(CURRENTLY_VIEWED_PROOFS + 12);
	       $("#proofs").html(msg);
	});
}
function getidsofsetandtype() {
	$.post("php/proofing.php", {
	      'func': 'browse',
	      'type': BROWSING_TYPE,
	      'list': 'true',
	      'set_name': SETNAME,
	      'location': CURRENTLY_VIEWED_PROOFS
	}, function(msg){
		LISTOFCURRENTIMAGEIDS = eval(msg);
		if (LISTOFCURRENTIMAGEIDS != null) {
		$("#out_of").html(LISTOFCURRENTIMAGEIDS.length);
		} else {
			$("#out_of").html(0);
		}
		debug.log(LISTOFCURRENTIMAGEIDS);
	});
}

function check_progress_of_archive() {
	$.post("php/proofing.php", {
	      'func': 'get_progress'
	}, function(msg){
		var percent = 82 + eval(msg)*18;
		$("#download_pg").progressBar(percent);
		setTimeout(function(){
			if (ARCHIVE_FINISHED == false) {
				check_progress_of_archive();
			}
        }, 1000);
	});
}

function submitziplist() {
	$("#download_pg").progressBar(82);
	if (BROWSING_TYPE == 'edited') {
		var the_type = 'full edits';
	} else {
		var the_type = 'raw previews';
	}
	$.post("php/proofing.php", {
	      'func': 'ziplist',
	      'list': LISTOFCURRENTIMAGESTOZIP,
	      'id_list': LISTOFCURRENTIMAGEIDS,
	      'set_name': SETNAME,
	      'type': the_type
	}, function(msg){
		   if (BROWSING_TYPE == 'edited') {
			   $("#download_pg").progressBar(90);
			   $.post("php/proofing.php", {
				      'func': 'ziplist',
				      'list': LISTOFCURRENTIMAGESTOZIP2,
				      'id_list': LISTOFCURRENTIMAGEIDS,
				      'set_name': SETNAME,
				      'type': 'web edits'
				}, function(msg){
					ARCHIVE_FINISHED = true;
				       $("#downloadables").html(msg);
				       $("#download_pg").progressBar(100);
				       setTimeout(function(){
				    	   if (BROWSING_TYPE != 'downloads') {
				    		   $("#download_title").html('<a onclick="create_downloadables()" style="cursor: pointer;">Create Selected Set\'s Downloadable Archives</a>');
				    	   }
				    	   $("#download_pg").hide();
				    	   downloadsPreview();
				        }, 500);
				});
		   } else {
		   ARCHIVE_FINISHED = true;
	       $("#downloadables").html(msg);
	       $("#download_pg").progressBar(100);
	       setTimeout(function(){
	    	   if (BROWSING_TYPE != 'downloads') {
	    		   $("#download_title").html('<a onclick="create_downloadables()" style="cursor: pointer;">Create Selected Set\'s Downloadable Archives</a>');
	    	   }
	    	   $("#download_pg").hide();
	    	   downloadsPreview();
	        }, 500);
		   }
	});
}

function getzipjson(image_id, type) {
	if (isInt(image_id)) {
		if (BROWSING_TYPE == 'edited') {
			var image_location = "image2.php?id=" + image_id + "&t=f&height=824&location=true&e=.jpg";
			var image_location2 = "image2.php?id=" + image_id + "&t=ew&height=824&location=true&e=.jpg";
		} else {
			var image_location = "image2.php?id=" + image_id + "&t=w&height=824&location=true&e=.jpg";
		}
		$.getJSON(image_location, function(json){
			LISTOFCURRENTIMAGESTOZIP.push(json);
			if (BROWSING_TYPE == 'raw') {
				$("#download_pg").progressBar(LISTOFCURRENTIMAGESTOZIP.length/LISTOFCURRENTIMAGEIDS.length*80);
				if (type == 'recurse' && LISTOFIMAGEIDSLEFT.length > 0) {
					getzipjson(LISTOFIMAGEIDSLEFT.pop(), 'recurse');
				}
			} else {
				$("#download_pg").progressBar((LISTOFCURRENTIMAGESTOZIP.length+LISTOFCURRENTIMAGESTOZIP2.length)/(LISTOFCURRENTIMAGEIDS.length*2)*80);
				$.getJSON(image_location2, function(json){
					LISTOFCURRENTIMAGESTOZIP2.push(json);
					$("#download_pg").progressBar((LISTOFCURRENTIMAGESTOZIP.length+LISTOFCURRENTIMAGESTOZIP2.length)/(LISTOFCURRENTIMAGEIDS.length*2)*80);
					if (type == 'recurse' && LISTOFIMAGEIDSLEFT.length > 0) {
						getzipjson(LISTOFIMAGEIDSLEFT.pop(), 'recurse');
					}
				});
			}
			//debug.log(LISTOFCURRENTIMAGESTOZIP.length, LISTOFCURRENTIMAGEIDS.length, LISTOFCURRENTIMAGESTOZIP.length/LISTOFCURRENTIMAGEIDS.length*80);
			
			if (LISTOFCURRENTIMAGESTOZIP.length == LISTOFCURRENTIMAGEIDS.length) {
				submitziplist();
			}
			//debug.log(LISTOFCURRENTIMAGESTOZIP);
		});
	}
}

function create_downloadables() {
	ARCHIVE_FINISHED = false;
	$("#downloads_btn").show();
	$("#downloads_spacer").show();
	$("#download_title").html("Creating Archive");
	$("#download_pg").progressBar({ showText: false, barImage: 'images/progressbg_black.gif', stepDuration: 60});
	$("#download_pg").show();
	setTimeout(function(){
	LISTOFCURRENTIMAGESTOZIP = [];
	if (LISTOFCURRENTIMAGEIDS.length <= 10) {
	for (var i in LISTOFCURRENTIMAGEIDS) {
		getzipjson(LISTOFCURRENTIMAGEIDS[i], 'regular');
	}
	} else {
		for (var i in LISTOFCURRENTIMAGEIDS) {
			LISTOFIMAGEIDSLEFT.push(LISTOFCURRENTIMAGEIDS[i]);
		}
		for(i=1;i<=10;i++) {
			getzipjson(LISTOFIMAGEIDSLEFT.pop(), 'recurse');
		}
	}
	}, 500);
}

function previousRorE() {
    if (CURRENTLY_VIEWED_PROOFS > 0) {
        CURRENTLY_VIEWED_PROOFS = CURRENTLY_VIEWED_PROOFS - 12;
    }
    if (CURRENTLY_VIEWED_PROOFS < 0) {
        CURRENTLY_VIEWED_PROOFS = 0;
    }
    RorE();
}

function nextRorE() {
    CURRENTLY_VIEWED_PROOFS = CURRENTLY_VIEWED_PROOFS + 12;
    RorE();
}

function set_name_change() {
	SETNAME = $("#set_name").val();
	debug.log($("#set_name").val());
	RorE();
	getidsofsetandtype();
}

function loadHome() {
    TOP_LEVEL = TOP_HOME;
    SUB_LEVEL = SUB_HOME;
    subLoad(SUB_LEVEL);
}

function changePass() {
    if ($("#password1").val() == $("#password2").val()) {
        var password = $("#password1").val();
        $.post("php/client.php", {
            'func': 'modifyPass',
            'pass': password
        }, function(msg){
            subLoad(SUB_LEVEL);
        });
    }
}

function logout() {
    $.post("php/login.php?logout=true", function(data){
		SUB_LEVEL = 'log_in';
        subLoad(SUB_LEVEL);
   	});
}

function login() {
    var email = $("#email").val();
    var pass = $("#pass").val();
    $.post("php/login.php?email=" + email + "&pass=" + pass, function(data){
        if (data == 'Login Successful') {
            $("#section").animate({opacity: 0.01}, 750);
			SUB_LEVEL = 'log_out';
            subLoad(SUB_LEVEL);
        } else {
            alert(data);   
        }
   	});
}

function checkDate() {
    var date = $("#year").val() + "-" + $("#month").val() + "-" + $("#day").val();
    $.post("php/calendar.php", {
      'date': date
    }, function(msg){
	  $("#section").animate({opacity: 0.01}, 450, function(){
		$("#section").html(msg);
		$("#section").animate({opacity: 1}, 450);
	  });
	});
}

function bookDate() {
    var date = $("#year").val() + "-" + $("#month").val() + "-" + $("#day").val();
	var package = 'none';
	$('input[name=package]:radio').each(function() {
	  if ($(this).attr('checked')) {
		package = $(this).val();
	  }
	});
	if (package == 'none') {
	  alert('Please select a package.');
	} else {
    $.post("php/booking.php", {
      'date': date,
	  'package': package
    }, function(msg){
	  $("#section").animate({opacity: 0.01}, 450, function(){
		$("#section").html(msg);
		$("#section").animate({opacity: 1}, 450);
	  });
	});
	}
}


function sendmessage() {
	var email = $("#email").val();
    var message = $("#message").val();
    var subject = $("#subject").val();
	var phone = $("#phone").val();
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (email != 'email@domain.com') {
        if (filter.test(email)) {
			$.post("php/mailer.php",{
			  'email':email,
			  'subject':subject,
			  'message':message,
			  'phone':phone
			}, function(data){
			  $("#section").animate({opacity: 0.01}, 450, function(){
				$("#section").html(data);
				$("#section").animate({opacity: 1}, 450);
			  });
                //alert("Message Sent");
            });
        } else {
            alert("Please input a valid email address.");
        }
    } else {
        alert("Please input your email so that I can get back to you.");
    }
}


PATRONS = [
	new Patron(246, 550, "url('images/man1.png')"),
	new Patron(300, 500, "url('images/patron2.png')"),
	new Patron(136, 370, "url('images/patron.png')")
];

function Patron(width, height, filename) {
    this.width = width;
    this.height = height;
    this.filename = filename;
}

function Photograph(orientation, thumbnail, width, height, filename) {
    this.orientation = orientation;
    this.thumbnail = thumbnail;
    this.width = width;
    this.height = height;
    this.filename = filename;
}

function Frame(number, photograph) {
    this.number = number;
    this.photograph = photograph;
}

function locationLoader() {
    LOADING_SECTION = true;
    var url_parts = URL.split('#');
    if(url_parts.length > 1) {
    	var extra_parts = url_parts[1].split('!');
    	if (extra_parts.length > 1) {
    		var extravars = '&extra=' + extra_parts[1];
    		url_parts[1] = extra_parts[0];
    	} else {
			var extra_parts = url_parts[1].split('%21');
			if (extra_parts.length > 1) {
			  var extravars = '&extra=' + extra_parts[1];
			  url_parts[1] = extra_parts[0];
			} else {
			  var extravars = '';
			}
    	}
        var section_parts = url_parts[1].split('/');
        TOP_LEVEL = section_parts[0];
    	if ($(window).width() <= 1200 && TOP_LEVEL == 'blog') {
    		$("#leftGrad").css("opacity", "0.01");
    		$("#rightGrad").css("opacity", "0.01");
    	}
        if (section_parts.length > 2) {
           SUB_LEVEL = section_parts[1];
           $.ajax({
               type: "POST",
               url: "php/section.php?top=" + TOP_LEVEL + "&sub=" + SUB_LEVEL + extravars,
               success: function(msg){
				 $.getJSON("php/mlist.php?level=selected&func=json&top=" + TOP_LEVEL + "&sub=" + SUB_LEVEL, function(json){
                      document.title = json.title;
                   });
                 LOADING_SECTION = false;
                 $("#section").html(msg);
				 gotoPost(extravars);
                 $("#top").load("php/mlist.php?level=top&top=" + TOP_LEVEL + "&sub=" + SUB_LEVEL);
                 $("#sub").load("php/mlist.php?level=sub&top=" + TOP_LEVEL + "&sub=" + SUB_LEVEL);
                 $("#selected").load("php/mlist.php?level=selected&top=" + TOP_LEVEL + "&sub=" + SUB_LEVEL);
               }
           });
        } else {
		  $.getJSON("php/mlist.php?level=selected&func=json&top=" + TOP_LEVEL, function(json){
                 SUB_LEVEL = json.sublevel;
                 document.title = json.title;
                
                 $.ajax({
                   type: "POST",
                   url: "php/section.php?top=" + TOP_LEVEL + "&sub=" + SUB_LEVEL + extravars,
                   success: function(msg){
                     LOADING_SECTION = false;
                     $("#section").html(msg);
					 gotoPost(extravars);
                     $("#top").load("php/mlist.php?level=top&top=" + TOP_LEVEL + "&sub=" + SUB_LEVEL);
                     $("#sub").load("php/mlist.php?level=sub&top=" + TOP_LEVEL + "&sub=" + SUB_LEVEL);
                     $("#selected").load("php/mlist.php?level=selected&top=" + TOP_LEVEL + "&sub=" + SUB_LEVEL);
                   }
                 });
		  });
        }
    } else {
            $("#top").load("php/mlist.php?level=top&top=" + TOP_HOME);
            $("#sub").load("php/mlist.php?level=sub&top=" + TOP_HOME);
            $("#selected").load("php/mlist.php?level=selected&top=" + TOP_HOME);
            TOP_LEVEL = TOP_HOME;
            SUB_LEVEL = SUB_HOME;
            loadSection();
    }
	pageTracker._trackPageview('/' + TOP_LEVEL + '/' + SUB_LEVEL);
}

function GoodBye() {
  pageTracker._trackPageview('/exit/goodbye');
}

function gotoPost(extravars) {
  //alert(extravars);
  if (extravars != '') {
	var extraextra = extravars.split('_');
	//alert(extraextra[0]);
	if (extraextra[0] == '&extra=post') {
	  //alert('post-' + extraextra[1]);
	  go_to_a_post = extraextra[1];
	}
  }
}


function checkURLChange() {
    if (URL != window.location.href && !LOADING_SECTION) {
        URL = window.location.href;
        LOADING_SECTION = true;
        var url_parts = URL.split('#');
        if (url_parts.length > 1) {
            var section_parts = url_parts[1].split('/');
            TOP_LEVEL = section_parts[0];
            if (section_parts.length > 2) {
                SUB_LEVEL = section_parts[1];
                subLoad(SUB_LEVEL);
            } else {
			  $.getJSON("php/mlist.php?level=selected&func=json&top=" + TOP_LEVEL, function(json){
				   SUB_LEVEL = json.sublevel;
                   topLoad(TOP_LEVEL);
			  });
            }
            
        } else {
           TOP_LEVEL = TOP_HOME;
           SUB_LEVEL = SUB_HOME;
           subLoad(SUB_LEVEL);
        }
    }
    URL = window.location.href;
}

//Run this once the DOM has been loaded 
$(document).ready(function() {  
    $.post("php/client.php",{
    	'func':'browser',
        'window_width':$(window).width(),
        'window_height':$(window).height(),
        'screen_width':screen.width,
        'screen_height':screen.height
    }, function(msg){
        locationLoader();
    });
    
    var window_height = $(window).height();
    if (window_height > 790) {
        ldiv = 530;
        pdiv = 580;
    }
    if (window_height > 970) {
        ldiv = 710;
        pdiv = 760;
    }   

    PHOTOGRAPHS = [
        new Photograph("landscape", false, (ldiv/1819)*2729 + 50, (ldiv/1819)*1819 + 65, "image2.php?id=25&t=drop&height=" + window_height + "&e=.jpg"),
        new Photograph("landscape", false, (ldiv/2000)*3008 + 50, (ldiv/2000)*2000 + 65, "image2.php?id=1940&t=drop&height=" + window_height + "&e=.jpg")
    ];
    
    if ($(window).height() <= 790) {
    	DEFAULT_SIZE = false;
        $("#floor").css("height", "90px");
        $("#viewport").css("margin", "0 auto -90px")
    }
    
    setInterval(checkURLChange, 1000);
    setInterval(checkDOCHeight, 100);
    
    $(".fancy").fancybox();

    ///////
});

function checkDOCHeight() {
    if ($(document).height() != OLD_DOCUMENT_HEIGHT) {
        OLD_DOCUMENT_HEIGHT = $(document).height();
        if (DEFAULT_SIZE == true) {
        	$("#leftGrad").height($(document).height() - 120 + "px");
        	$("#rightGrad").height($(document).height() - 120 + "px");
        } else {
        	$("#leftGrad").height($(document).height() - 90 + "px");
        	$("#rightGrad").height($(document).height() - 90 + "px");
        }
    }
}

function nextGalleryImage() {
    if (ANIMATEALL == false) {
        ANIMATEALL = true;
        animateSwitch();
    } else {
        ANIMATEALL = false;
    }
}

function checkAnimateSwitch() {
    if (ANIMATEALL == true) {
        animateSwitch();
    }
}

function animateMenu(topWidth, selectedWidth, subWidth) {
    CUR_LOADING_SECTION_ANI = false;
    ANIMATEALL = false;
        $("#top").animate({"width": topWidth}, 200);
        $("#selected").animate({"width": selectedWidth}, 200);
        $("#sub").animate({"width": subWidth}, 200, function(){
    	    $("#top").load("php/mlist.php?level=top&top=" + TOP_LEVEL + "&sub=" + SUB_LEVEL, function(){
                $("#sub").load("php/mlist.php?level=sub&top=" + TOP_LEVEL + "&sub=" + SUB_LEVEL, function(){
                    $("#sub").animate({opacity: 1}, 750);
                    $("#top").animate({opacity: 1}, 750);
                });
            });
        });
    
    
    	$("#selected").load("php/mlist.php?level=selected&top=" + TOP_LEVEL + "&sub=" + SUB_LEVEL, function(){
            $("#selected").animate({"height": "35px"}, 200, function(){
                loadSection();
    	        $("#selected").animate({opacity: 1}, 1700, function(){
            	
                });
            });
        });
        
}

function topLoad(level) {
    LOADING_SECTION = true;
    TOP_LEVEL = level;
    ANIMATEALL = true;
    $("#rightGrad").animate({opacity: 0.01}, 2150);
    $("#leftGrad").animate({opacity: 0.01}, 2150);
    
    $("#sub").animate({opacity: 0.01}, 750);
    $("#top").animate({opacity: 0.01}, 750);
    $("#selected").animate({opacity: 0.01}, 750, function(){
        CUR_LOADING_SECTION_ANI = true;
    });
    

	$.getJSON("php/mlist.php?level=selected&func=json&top=" + TOP_LEVEL, function(json){
         SUB_LEVEL = json.sublevel;
         document.title = json.title;
         selectedWidth = json.selected_width + "px";
         topWidth = json.top_width + "px";
         subWidth = json.sub_width + "px";
         if (CUR_LOADING_SECTION_ANI) {
             animateMenu(topWidth, selectedWidth, subWidth);
         } else {
             setTimeout(function(){
                 if (CUR_LOADING_SECTION_ANI) {
                     animateMenu(topWidth, selectedWidth, subWidth);
                 }
             }, 100);
             setTimeout(function(){
                 if (CUR_LOADING_SECTION_ANI) {
                     animateMenu(topWidth, selectedWidth, subWidth);
                 }
             }, 200);
             setTimeout(function(){
                 if (CUR_LOADING_SECTION_ANI) {
                     animateMenu(topWidth, selectedWidth, subWidth);
                 }
             }, 300);
             setTimeout(function(){
                 if (CUR_LOADING_SECTION_ANI) {
                     animateMenu(topWidth, selectedWidth, subWidth);
                 }
             }, 450);
             setTimeout(function(){
                 if (CUR_LOADING_SECTION_ANI) {
                     animateMenu(topWidth, selectedWidth, subWidth);
                 }
             }, 680);
             setTimeout(function(){
                 if (ANIMATEALL) {
                     animateMenu(topWidth, selectedWidth, subWidth);
                 }
             }, 800);
         }
       }
	);
    
    
}

function fullLoad(toplev, sublev) {
  TOP_LEVEL = toplev;
  SUB_LEVEL = sublev;
  subLoad(sublev);
}

function subLoad(level) {
    LOADING_SECTION = true;
    SUB_LEVEL = level;
    ANIMATEALL = true;
    $("#rightGrad").animate({opacity: 0.01}, 2150);
    $("#leftGrad").animate({opacity: 0.01}, 2150);
    
    $("#sub").animate({opacity: 0.01}, 750);
    $("#top").animate({opacity: 0.01}, 750);
    $("#selected").animate({opacity: 0.01}, 750);
    
	$.getJSON("php/mlist.php?level=selected&func=json&top=" + TOP_LEVEL + "&sub=" + SUB_LEVEL, function(json){
         document.title = json.title;
         selectedWidth = json.selected_width + "px";
         topWidth = json.top_width + "px";
         subWidth = json.sub_width + "px";
         if (CUR_LOADING_SECTION_ANI) {
             animateMenu(topWidth, selectedWidth, subWidth);
         } else {
             setTimeout(function(){
                 if (CUR_LOADING_SECTION_ANI) {
                     animateMenu(topWidth, selectedWidth, subWidth);
                 }
             }, 100);
             setTimeout(function(){
                 if (CUR_LOADING_SECTION_ANI) {
                     animateMenu(topWidth, selectedWidth, subWidth);
                 }
             }, 200);
             setTimeout(function(){
                 if (CUR_LOADING_SECTION_ANI) {
                     animateMenu(topWidth, selectedWidth, subWidth);
                 }
             }, 300);
             setTimeout(function(){
                 if (CUR_LOADING_SECTION_ANI) {
                     animateMenu(topWidth, selectedWidth, subWidth);
                 }
             }, 450);
             setTimeout(function(){
                 if (CUR_LOADING_SECTION_ANI) {
                     animateMenu(topWidth, selectedWidth, subWidth);
                 }
             }, 680);
             setTimeout(function(){
                 if (ANIMATEALL) {
                     animateMenu(topWidth, selectedWidth, subWidth);
                 }
             }, 800);
         }
       }
	);
}

function blog_load_page(page) {
	LOADING_SECTION = true;
	scroll(0,0);
	EXTRA = '&extra=page_' + page;
	loadSection();
	EXTRA = '';
}

function loadSection() {
    $.ajax({
       type: "POST",
       url: "php/section.php?top=" + TOP_LEVEL + "&sub=" + SUB_LEVEL + EXTRA,
       success: function(msg){
         $("#section").animate({opacity: 0.01}, 750, function(){
             $("#leftGrad").height($(window).height() - 50 + "px");
             $("#rightGrad").height($(window).height() - 50 + "px");
             $("#section").html(msg);
             $("#img0").attr('src', PHOTOGRAPHS[CURRENT_IMAGE].filename);
             $("#img1").attr('src', PHOTOGRAPHS[CURRENT_IMAGE].filename);
             positionImage();
             if (PHOTOGRAPHS[CURRENT_IMAGE].orientation == "landscape") {
                 $("#navigator").fadeIn("slow");
             } else {
                 $("#navigatorPort").fadeIn("slow");
             }
             setTimeout(function(){
            	if ($(window).width() <= 1200 && TOP_LEVEL == 'blog') {
            		$("#leftGrad").height($(document).height() + "px");
            		$("#rightGrad").height($(document).height() + "px");
            	} else {
            		$("#leftGrad").height($(document).height() + "px");
            		$("#rightGrad").height($(document).height() + "px");
            		$("#rightGrad").animate({opacity: 1}, 550);
            		$("#leftGrad").animate({opacity: 1}, 550);
            	}
                $(".fancy").fancybox();
                LOADING_SECTION = false;
             }, 1000);
             $("#section").animate({opacity: 1}, 750);
         });
       }
    });
}


//Run this function once everything has been downloaded
window.onload = PageLoaded; 

function PageLoaded() {
    PAGE_LOADED = true;
    if (LOAD_TIME_PASSED == true) {
        setTimeout('displayLoadedPage()', 1000);
    }
}

//Display loading screen for a minimum time
window.setTimeout('TimeoutPassed()', 2000 );

function TimeoutPassed() {
    LOAD_TIME_PASSED = true;
    if (PAGE_LOADED == true) {
        displayLoadedPage();
    }
}


//Fade in page after being loaded
function displayLoadedPage() {
    $("#img0").attr('src', PHOTOGRAPHS[0].filename);
    $("#whitespace").fadeOut("slow")
    $("#viewport").fadeIn("slow");
    $("#navigator").fadeIn("slow");
    $("#floor").fadeIn("slow");
    $("#topmenu").slideDown("slow");
	positionImage();
    //setTimeout('positionImage()', 500);
    setTimeout(function(){
	  if (TOP_LEVEL == 'gallery') {
		//nextGalleryImage();
	  }
	}, 4500);
	if (go_to_a_post != '') {
	  setTimeout(function(){
		document.getElementById('post-' + go_to_a_post).scrollIntoView(true);
	  }, 2000);
	}
    $("#leftGrad").height($(document).height() + "px");
    $("#rightGrad").height($(document).height() + "px");
}



function blog_width_tester() {
	if ($(window).width() <= 1200 && TOP_LEVEL == 'blog') {
		$("#leftGrad").fadeOut("slow");
		$("#rightGrad").fadeOut("slow");
	} else {
		$("#leftGrad").animate({opacity: 1}, "slow");
		$("#rightGrad").animate({opacity: 1}, "slow");
		$("#leftGrad").fadeIn("slow");
		$("#rightGrad").fadeIn("slow");
	}
}

//~Run this every time the window is resized
$(window).resize(function() {
	blog_width_tester();
    positionImage();
});

//Switch the variables around for future reference
function switchImages() {
    if (VIEWED_IMAGE.number == "#imageArea0") {
        VIEWED_IMAGE.number = "#imageArea1"
        HIDDEN_IMAGE.number = "#imageArea0"
    } else {
        VIEWED_IMAGE.number = "#imageArea0"
        HIDDEN_IMAGE.number = "#imageArea1"
    }
    VIEWED_IMAGE.photograph = HIDDEN_IMAGE.photograph;
    HIDDEN_IMAGE.photograph = VIEWED_IMAGE.photograph;
}

//Animates the change between current image and selected image
function animateSwitch() {
    ANIMATING = true;
    if (CURRENT_IMAGE < PHOTOGRAPHS.length -1) {
        CURRENT_IMAGE = CURRENT_IMAGE + 1;
    } else {
        CURRENT_IMAGE = 0;
    }
	pageTracker._trackPageview('/gallery/image/' + CURRENT_IMAGE);

	
    if (HIDDEN_IMAGE.number == "#imageArea0") {
        var imageid = "#img0";
    } else {
        var imageid = "#img1";
    }
    $(imageid).attr('src', PHOTOGRAPHS[CURRENT_IMAGE].filename);
    HIDDEN_IMAGE.photograph = CURRENT_IMAGE;
    
    positionImage();
    //Set Patron list
   
    
    //set variables for animation

    viewedImageL = 0 - PHOTOGRAPHS[VIEWED_IMAGE.photograph].width - 30;
    viewedImageLFinal = $(window).width() + 30;
    
    hiddenPosL = PHOTOGRAPHS[VIEWED_IMAGE.photograph].width + 30 + getFrameLeft(VIEWED_IMAGE.photograph) + getFrameLeft(HIDDEN_IMAGE.photograph);
    if (hiddenPosL < $(window).width()) {
        hiddenPosL = $(window).width() + 30;
        frameSpace = hiddenPosL - getFrameLeft(VIEWED_IMAGE.photograph) - PHOTOGRAPHS[VIEWED_IMAGE.photograph].width;
        viewedImageL = getFrameLeft(HIDDEN_IMAGE.photograph) - frameSpace - PHOTOGRAPHS[VIEWED_IMAGE.photograph].width;
    }

    $(HIDDEN_IMAGE.number).css({'left' : hiddenPosL});
    
    floorPos = parseInt($("#floor").css('background-position')) - (getFrameLeft(VIEWED_IMAGE.photograph) - viewedImageL);
    if ($("#floor").css('background-position') == undefined) {
    	floorPos = parseInt($("#floor").css('background-position-x')) - (getFrameLeft(VIEWED_IMAGE.photograph) - viewedImageL);
    }
    //$("#floor").css({"width": parseInt($("#floor").css('width')) + parseInt($(VIEWED_IMAGE.number).css('left')) + $(VIEWED_IMAGE.number).width() + 30 });
    
    $("#leftGrad").fadeOut("slow");
    $("#navigator").fadeOut("slow");
    $("#navigatorPort").fadeOut("slow");
    $("#patron").fadeOut("slow");
    $("#rightGrad").fadeOut("slow", function callback() {
        if (PHOTOGRAPHS.length != CURRENT_IMAGE + 1) {
            var preloadNextImage = new Image();
            $(preloadNextImage).attr('src', PHOTOGRAPHS[CURRENT_IMAGE + 1].filename);
        }
        $(VIEWED_IMAGE.number).animate( { left: viewedImageL }, 6000 );
        $(HIDDEN_IMAGE.number).animate( { left: getFrameLeft(HIDDEN_IMAGE.photograph) }, 6000 );
        bposition = "(" + floorPos + "px" + " 0px)";
        $("#floor").animate( {backgroundPosition: floorPos + " 0px"}, 6000, function callback() {
            pNumber = Math.floor(Math.random()*PATRONS.length);
            $("#leftGrad").fadeIn("slow");
            $("#rightGrad").fadeIn("slow");
            
            if (PHOTOGRAPHS[CURRENT_IMAGE].orientation == "landscape") {
                $("#navigator").fadeIn("slow");
                patronPos = getFrameLeft(HIDDEN_IMAGE.photograph) - PATRONS[pNumber].width + 20;
            } else {
                $("#navigatorPort").fadeIn("slow");
                patronPos = getFrameLeft(HIDDEN_IMAGE.photograph) + $(HIDDEN_IMAGE.number).width() + 20;
            }
            
            
            $(VIEWED_IMAGE.number).css({'left' : viewedImageLFinal});
            switchImages();
            
            $("#patron").css({'left' : patronPos, 'width' : PATRONS[pNumber].width, 'height' : PATRONS[pNumber].height, 'background-image' : PATRONS[pNumber].filename});
            
            ramdon = Math.floor(Math.random()*3);
            setTimeout('$("#patron").fadeIn(1500)', 500);;
            //Randomly display patron or not
            //if (ramdon == 1 || ramdon == 2) {
                //setTimeout('$("#patron").fadeIn(1500)', 500);;
            //}
            positionImage();
            ANIMATING = false;
            setTimeout(checkAnimateSwitch, 3000);
        });
    });
}

/*
 *  get Frame's Position in the viewport
 *  Referenced by animateSwitch and positionImage
 */

function getFrameTop(photograph) {
    var top = 0;
    if (PHOTOGRAPHS[photograph].orientation == "landscape") {
        top = (($(window).height() / 7) * 6) / 2 - PHOTOGRAPHS[photograph].height/2;
    } else {
        top = ($(window).height() - 190)/2 - PHOTOGRAPHS[photograph].height/2 + 60;
        if ($(window).height() <= 790) {
            top = top + 7;
        }
    }
    if ($(window).height() <= 790) {
        top = top + 15;
    }
    return top;
}

function getFrameLeft(photograph) {
    if (PHOTOGRAPHS[photograph].orientation == "landscape") {
        return $(window).width()/2 - PHOTOGRAPHS[photograph].width/2;
    } else {
        floorTop = $(window).height() * 0.83;
        bottomOfViewed = getFrameTop(0) + PHOTOGRAPHS[0].height - 30;
        groupWidth = $("#navigatorPort").width() + (floorTop - bottomOfViewed)/2 - 70 + PHOTOGRAPHS[photograph].width;
        return ($(window).width()/2 - (groupWidth/2)) + $("#navigatorPort").width() + (floorTop - bottomOfViewed)/2 - 140;
    }
}


//Positions the images in their proper places
function positionImage() {
    floorTop = $(window).height() - 120;
    if (PHOTOGRAPHS[VIEWED_IMAGE.photograph].orientation == "landscape") {
        bottomOfViewed = getFrameTop(VIEWED_IMAGE.photograph) + PHOTOGRAPHS[VIEWED_IMAGE.photograph].height - 30;
    } else {
        bottomOfViewed = getFrameTop(0) + PHOTOGRAPHS[0].height - 30;
    }
    
    navigatorPosL = $(window).width()/2 - $("#navigator").width()/2;
    navigatorPosT =  bottomOfViewed + (floorTop - bottomOfViewed)/2 - 25;
    if ($(window).height() <= 790) {
        navigatorPosT = navigatorPosT + 15;
    }
    
    
    navigatorPortL = $(window).width()/2 + (PHOTOGRAPHS[VIEWED_IMAGE.photograph].width )/2 - 55;
    navigatorPortT = ((($(window).height()/6)*5)+$("#topmenu").height())/2 - $("#navigatorPort").height()/2;
    
    
    $(VIEWED_IMAGE.number).css({'top' : getFrameTop(VIEWED_IMAGE.photograph), 'left' : getFrameLeft(VIEWED_IMAGE.photograph)});
    $(HIDDEN_IMAGE.number).css({'top' : getFrameTop(HIDDEN_IMAGE.photograph), 'left' : $(window).width() + 30});
    $("#navigator").css({'top' : navigatorPosT, 'left' : navigatorPosL});
    $("#navigatorPort").css({'top' : navigatorPortT, 'left' : navigatorPortL});
}

