/* putting in here so we're not calling yet another external file */

/** 
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


/*start of custom code */

function get_url_values() {
	//borrows heavily from http://www.bennadel.com/blog/695-Ask-Ben-Getting-Query-String-Values-In-JavaScript.htm
	var url_values = new Object();

	window.location.search.replace(
		new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
			function( $0, $1, $2, $3 ){
				url_values[ $1 ] = $3;
				}
		);
	
	return url_values;
	}

function show_sub(id) {
	hide_sub($('.sub_nav:visible').attr('id'));
	
	$('#' + id).slideDown(700, function() {
			//animation done
			if(typeof(fuzzy_bg) != 'undefined')
				change_bg(fuzzy_bg);
			}
		);	
	}

function hide_sub(id) {
	$('#' + id + ' .selected').removeClass('selected');

	$('#' + id).slideUp(700, function() {
		//animation done
		if($('.sub_nav:visible').length == 0) {
			if(typeof(background_image) != 'undefined')
				change_bg(background_image);
			}
		});
	}	

function get_random_image(bgs) {
	prefix = '';
	var total_num = bgs.length - 1;

	if($.cookie('bg_index') != null && $.cookie('bg_index') < total_num) {
		var index = $.cookie('bg_index');
		}
	else {
		var index = Math.floor(Math.random()*total_num);
		$.cookie('bg_index', index, { expires: 1, path: '/', domain: 'thresholdfurniture.com'});
		}
		
	var new_bg_path = prefix + bgs[index].standard;
	var new_fuzzy_path = prefix + bgs[index].fuzzy;
	
	var paths = {'standard': new_bg_path, 'fuzzy': new_fuzzy_path};
	return paths;
	}
	
function change_bg(image_path) {
	if($('#background_img').length < 1) {
		var bg_el = $('<img />').attr('id', 'background_img').addClass('bg').attr('src', './blank.gif');
		bg_el.insertBefore('#content');
		}
	else {
		var bg_el = $('#background_img');
		}
	var current_path = bg_el.attr('src');
	if(typeof(image_path) == 'undefined' || image_path.length < 2) { 
		image_path = get_random_image();
		while(image_path == current_path) {
			image_path = get_random_image();
			}
		}
	bg_el.attr('src', image_path); 
	}

function show_gallery() {
	$('#display_images').show();
	$('#display_images').animate({
		top: 0
		},700, function() {
			show_caption();
			if($('#display_images li').length) {
				$('#display_controls').show();
				}
			$('#display_images').show();
			}
		);
	}

function show_caption() {
	$('#display_caption').slideDown(700);	
	}
	
function hide_gallery() {
	$('#display_controls').hide();
	hide_caption('both');
	}

function hide_caption(which) {
	$('#display_caption').slideUp(700, function() {
		$('#display_caption').hide();
		if(which == 'both') {
			$('#display_images').animate({
				top: '-320px'
				}, 700, function() {
					$('#display_images').hide();
				});
			}
		});
	}
	
function get_numeric_class(num) {
	var classes = new Array('zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine');
	
	if(num <= 9)
		return classes[num];
	else {
		var tens_digit = Math.floor(num/10);
		var ones_digit = num % 10;
		var class_base = classes[tens_digit];
		var tens_class = class_base + 'ten';
		var ones_class = classes[ones_digit];
		
		return tens_class + ' ' + ones_class; 
		}
	}
	
function get_gallery(div, lis) {
	$('#display_images').remove();
	
	var list_base = $('<ul></ul>');
	list_base.attr('id', 'display_images');
	
	if(typeof(lis) != 'undefined' && lis.length > 0) {
		for(i = 0; i < lis.length; i++) {
			class_text = get_numeric_class(i);
			
			var li = $('<li></li>').addClass(class_text).appendTo(list_base);
			var gallery_img = $('<img />').attr('src', lis[i].src);
			if(i == 0) {
				gallery_img.appendTo(li).load(function() {
					list_base.appendTo(div);
					show_gallery();
					});
				}
			else {
				gallery_img.appendTo(li);
				}
			}
		}
	}

function get_caption(caption_array, which_body, space) {
	
	var c_body = caption_array['body'][which_body];
	var caption_html = '';
	
	caption_html += '<h2>' + caption_array['title'] + '</h2>';
	for(c = 0; c < c_body.length; c++) {
		caption_html += c_body[c];
		}
	
	space.html(caption_html);
	}

function get_image_caption(slide_shown, space) {
	var caption_html = '';
	if(typeof(slide_shown) == 'undefined')
		return;
		
	if(typeof(g_images[slide_shown]) != 'undefined' && typeof(g_images[slide_shown].title) != 'undefined' && g_images[slide_shown].title.length > 2) {
		caption_html += '<h2>' + g_images[slide_shown].title + '</h2>';
		}
	else {
		caption_html += '<h2>' + caption.title + '</h2>';
		}

	if(typeof(g_images[slide_shown].caption) != 'undefined' && g_images[slide_shown].caption.length > 2) {
		caption_html += g_images[slide_shown].caption;
		}
	else {
		caption_html += caption.body[1];
		}
		
	space.html(caption_html);
	}

function display_gallery(g_images, caption, which) {
	if(typeof(g_images) != 'undefined' && g_images.length > 0) {
		get_gallery(gallery_space, g_images);
		}
	else {
		g_images == new Array('');
		get_gallery(gallery_space, g_images);
		}
	
	if(typeof(caption) != 'undefined' && $(caption).length > 0) {
		get_caption(caption, 1, caption_space);
		}
	else {
		hide_caption();
		}
	}
	
function open_page(page_id) {
	$('#' + page_id + ' a').click();
	}
	
function page_init() {
	/*config*/
	con_gallery_width = 520;
	con_base_url = location.protocol + '//' + location.host;
	//con_base_url += '/clients/threshold';
	
	//set the default easing to be used
	jQuery.easing.def = 'easeInOutQuart';
	
	//used to track which gallery images is currently shown for caption purposes
	//wasn't really planning on this so it wasn't built in more robustly, this should work fine however
	slide_shown = 0;

	/*get the bg image we'll be using for this visit*/
	$.get(con_base_url + '/includes/processing.php', {'action':'get_backgrounds'}, function(data) {
		bgs = data.bgs;

		var backgrounds = get_random_image(bgs);
		background_image = backgrounds.standard;
		fuzzy_bg = backgrounds.fuzzy;
		if($('#primary_nav .selected, #blog_primary_nav .selected').length > 0) {
			change_bg(fuzzy_bg);
			}
		else {	 
			change_bg(background_image);
			}
		}, 'json');
		
	$('.sub_nav').hide();
	
	gallery_space = $('#display');
	caption_space = $('#display_caption');
	g_images = '';
	caption = '';
	
	$('#primary_nav a').click(function(e) {
		var this_id = $(this).parent('#primary_nav li').attr('id');
		
		//blog doesn't need to be animated or handled just marked selected
		if(this_id == 'blog') {
			$('#primary_nav li a').removeClass('selected');
			$(this).addClass('selected');
			return;
			}
		
		e.preventDefault();
		if($(this).hasClass('selected')) {
			$(this).removeClass('selected');
			hide_sub(this_id + '_sub');
			}
		else {
			$('#primary_nav li a').removeClass('selected');
			$(this).addClass('selected');
			show_sub(this_id + '_sub');
			}
		hide_gallery();
		});
		
	$('.sub_nav a').click(function(e) {
		$('.sub_nav a').removeClass('selected');
		$(this).addClass('selected');
		
		//download sub menu will not pull up a gallery and instead just needs to show the files
		if($(this).parents('ul.sub_nav').attr('id') == 'download_sub') {
			return;
			}
			
		e.preventDefault();
		
		var cat_name = $(this).attr('id');
		$.get(con_base_url + '/includes/processing.php', {'category': cat_name, 'action':'get_gallery', 'new':'true'}, function(data) {
			g_images = $(data.g_images);
			
			caption = {
				'title': data.title,
				'body': { 1: [data.caption]}
				};
			
			display_gallery(g_images, caption);
			}, 'json');
		});

	$('#display_controls .next').click(function(e) {
		e.preventDefault();
		
		if(parseInt($('#display_images').css('left')) <= -(($('#display_images li').length - 1) * con_gallery_width)) {
			$('#display_images').animate({
				left: '-=' + con_gallery_width
				}).animate({
				left: con_gallery_width
				}, 0).animate({
				left: 0
				});
			slide_shown = 0;
			}
		else if(parseInt($('#display_images').css('left')) <= 0) {
			$('#display_images').animate({
				left: '-=' + con_gallery_width
				});
			slide_shown++;
			}
		
		get_image_caption(slide_shown, caption_space);
		});
	
	$('#display_controls .previous').click(function(e) {
		e.preventDefault();
		
		if(parseInt($('#display_images').css('left')) >= 0) {
			$('#display_images').animate({
				left: '+=' + con_gallery_width
				}).animate({
				left: -(($('#display_images li').length) * con_gallery_width)
				}, 0).animate({
				left: -(($('#display_images li').length - 1) * con_gallery_width)
				});
			slide_shown = $('#display_images li').length - 1;
			}
		else if(parseInt($('#display_images').css('left')) >= -(($('#display_images li').length - 1) * con_gallery_width)) {
			$('#display_images').animate({
				left: '+=' + con_gallery_width
				});
			slide_shown--;
			}
		
		get_image_caption(slide_shown, caption_space);
		});
	
	//see if a specific page is requested in the url
	var url_gets = get_url_values();
	if(typeof(url_gets['page']) != 'undefined' && url_gets['page'].length > 2) {
		open_page(url_gets['page']);
		}
	}