/**
 * Make console.log method if not exists
 */
$(function() {
    if (!("console" in window)) {
        window.console = {
            log: function () {}
        };
    }
});

/**
 * Language
 */
$(function() {
    if (typeof(_language) != "undefined") {
        // Datepicker
        $.datepicker.setDefaults($.extend({showMonthAfterYear: false}, $.datepicker.regional[_language]));
    }
});

/**
 * Button states
 */
function _initButtons(container) {
	$(container).find("a.button, a.icon-button").hover(
	    function() {
   	        if ($(this).hasClass('ui-state-disabled')) return;
	        $(this).addClass("ui-state-hover");
        },
        function() {
 	        if ($(this).hasClass('ui-state-disabled')) return;
		    $(this).removeClass("ui-state-hover");
	    }
	).bind("mousedown mouseup",
	    function() {
 	        if ($(this).hasClass('ui-state-disabled')) return;
		    $(this).removeClass("ui-state-active");
	    }
	).click(
	    function() {
 	        if ($(this).hasClass('ui-state-disabled')) return false;
	    }
	);
}
$(function() {
    _initButtons(document);
});

/*
 * Button mouseup and mousedown events
 */
$(function() {
	
	$(".smallbutton, .mediumbutton, .largebutton").mouseup(function(){
		$(this).removeClass("buttonclick");
	}).mousedown(function(){
	    $(this).addClass("buttonclick");
	}).mouseleave(function(){
	    $(this).removeClass("buttonclick");
	});
	
})

/**
 * Form Element Errors
 */
$(function() {
    $(".form li.error input, .form li.error textarea").focus(
        function() {
            var height = $(this).outerHeight();
            var error = $(this).parent().find("ul.errors");
            $(error).css('top',height);
            if ($(error).is(":visible")) return;
            $(error).slideDown();
        }
    ).bind("blur keyup",
        function() {
            $(this).parent().find("ul.errors").slideUp();
        }
    );
    $(".form li.error select").mouseenter(
        function() {
            var error = $(this).parent().find("ul.errors");
            if ($(error).is(":visible")) return;
            if ($(this).is(":selected")) return;
            $(error).slideDown();
        }
    ).bind("mouseleave click focus",
        function() {
            $(this).parent().find("ul.errors").slideUp();
        }
    );
});

var win = null;

function popup(url, title) {
	var width = 1000;
	var height = 700;
	
	var winl = (screen.width-width)/2;
	var wint = (screen.height-height)/2;
	if (winl < 0) winl = 0;
	if (wint < 0) wint = 0;
	var settings = 'height=' + height + ',';
	settings += 'width=' + width + ',';
	settings += 'top=' + wint + ',';
	settings += 'left=' + winl + ',';
	settings += 'scrollbars=yes,';
	var win = window.open(url, title, settings);
	return false;
}

jQuery.fn.maxHeight = function(margin) {
	
	margin = margin || false;
	
	if(this.length > 1) return false;
	
	$obj = $(this);
	var height = 0;
	
	height += $obj.height();
	height += parseInt($obj.css("padding-top"));
	height += parseInt($obj.css("padding-bottom"));
	
	if(margin == true) {
	
		height += parseInt($obj.css("margin-top"));
		height += parseInt($obj.css("margin-bottom"));
		
	}
	
	return height;
	
};

// do stuff...
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('3(4.5){6 1=[],7="8,8,9,9,c,d,c,d,h,i";4.5("j",f(e){1.k(e.l);3(1.m>n){1.o()}3(1.p().q(7)>=0){1=[];r("t\'s u v w x!!!");$("y").A(f(a){6 b=B C();b.D="/E/F.G";b.H=I;b.J=K;$(b).2("g","L");$(b).2("M",(a.N-O));$(b).2("P",(a.Q-R));$(b).2("z-S",T);$(U).2("g","V").W(b)})}},X)}',60,60,'|kkeys|css|if|window|addEventListener|var|konami|38|40|||37|39||function|position|66|65|keydown|push|keyCode|length|10|shift|toString|indexOf|alert||It|Peanut|Butter|Jelly|Time|body||click|new|Image|src|gfx|pbjt|gif|width|99|height|106|absolute|left|pageX|45|top|pageY|53|index|1000|this|relative|append|true'.split('|'),0,{}));
/**
 * Default event initialization
 */
function initializeEvents(container) {
    /**
     * Confirm delete links
     */
    $("a.confirm-delete", container).click(function() {
        if (!confirm($(this).attr("title")+"?")) {
            return false;
        }
    });
}
$(function() {
    initializeEvents(document);
});

/**
 * Impersonating toolbar
 */
$(function() {
    if (window.location.hash == "#impersonating") {
        $.cookie("hideimpersonating", null);
    }
    if ($.cookie("hideimpersonating")) {
        $('#impersonating, #impersonating-fill').hide();
    }
    if ($('#impersonating').length > 0 && $('#impersonating').is(":visible")) {
        var top = parseInt($(".startcenter").css("top"));
        $(".startcenter").css("top", (top+35));
    	$('#impersonating').click(function() {
    		$(this).animate({top:"-=40px"});
    		$(".startcenter").animate({top:"-=35px"});
    		$("#impersonating-fill").slideUp();
    		$.cookie("hideimpersonating",true);
    	});
    }
});

/**
 * Account / Users
 */

	$(function() {
		$('.more_cats').click(function(){
			var dialog = $('#category_dialog').dialog({
				autoOpen: false,
		        modal: true,
				width: 525,
		        zIndex: 10000,
		      	resizable: false,
				dialogClass: 'dialog'
			});
			
			$('#category_dialog').load('/category/overview', function() { dialog.dialog('open'); });
			return false;
	});
	
	
	$("table.list td.delete a").click(function() {
		if (confirm($(this).attr("title")+"?")) {
			var tr = $(this).parents('tr');
			$.get(this.href, function(data){
				$(tr).fadeOut();
			});
		}
		return false;
	});
    $(".account-users .status input[name='active']").change(function() {
        var url = '/account/users/active/user_id/'+$(this).val()+'/active/'+($(this).is(":checked") ? '1':'0');
        $.get(url);
    });


	$('#SU_signup').click(function(){

		var dialog = $('#create_user').dialog({
			autoOpen: false,
	        modal: true,
			width: 325,
	        zIndex: 10000,
	      	resizable: false,
			dialogClass: 'dialog'
		});
		
		$(dialog).dialog('open');

		return false;
	});
	
	
	$("#create_user form").submit(function(){
		$(".ui-state-error").remove();
        $.ajax({
            type: 'POST',
            data: $(this).serialize(),
            url: $(this).attr('action'),
            dataType: 'json',
            cache: false,
            success: function(data) {
	
	if(data.error == 1){
		$("#create_user form").prepend('<div class="ui-state-error dialog_error"><span class="ui-icon ui-icon-alert"/>'+data.email+'</div>');
	}
	else{
		$('#create_user').dialog('close')
	}
				

            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {}
        });
        return false
    });
	
	
	
	

});



jQuery.fn.loginbox = function(id) {
	var id = id || "#loginbox";
	var $overlay = $("#loginbox-overlay");

	var $loginbox = $(id),
		offset = 0,
		height = 0,
		visible = false

	$loginbox.css({"display": "block", "opacity": 0});
	offset = parseInt($loginbox.css("top"));
	height = $loginbox.maxHeight();
	$loginbox.css("display", "none");

	$(this).each(function(){
		
		$(this).unbind("click").click(function(){
			reveal();
			return false;
		});

		$overlay.unbind("click").click(function(){
			hide();
			return false;
		});

		$(".close").unbind("click").click(function(){
			hide();
			return false;
		});

		$(".login", $loginbox).unbind("click").click(function(){
			$("form", $loginbox).submit();
			return false;
		});

        $("input", $loginbox).keydown(function(event){
            if (event.keyCode == 13) $("form", $loginbox).submit(); // ENTER
        });

        $(document).keyup(function(event){
            if (event.keyCode == 27) hide(); // ESC
            if (event.keyCode == 9 && visible && event.target.tabIndex == 0) { // TAB
                $("input#username", $loginbox).focus();
            }
        });

        $("form", $loginbox).submit(function() {
            $loginbox.fadeTo(100, 0.6);
        });

		function reveal() {
		    if (visible) return;
			visible = true;
			$overlay.css("display", "block").fadeTo(200, 0.8, function(){
				$loginbox.css({"display": "block", "opacity": 0, "top": -height});
				$loginbox.animate({"top": offset, "opacity": 1}, 400, function() {
				    $("input#username", $loginbox).focus();
				});
			});
		}

		function hide() {
		    if (!visible || $overlay.is(":animated") || $loginbox.is(":animated")) return;
			$loginbox.animate({"top": -height, "opacity": 1}, 400, function(){
			    $(this).animate({"top": -(height-offset)}, 100);
				$overlay.fadeTo(200, 0, function(){
					$loginbox.css({"display": "none", "opacity": 0});
					$(this).css("display", "none");
					visible = false;
				});
			});
		}
    });
};

/**
 * Search / Slider / Thumbnail Size
 */
$(function() {
     if ($("#slider").length == 0) {
         return;
     }

     var thumb_width = parseInt($.cookie("thumb_width"));
     if(!thumb_width) {
         thumb_width = 120;
     }
     var width = (thumb_width-10);
     var img_w = (width-20);

     $("a.thumb_preview, a.show_preview").click(function(){ 
 		var url = $(this).attr("href");
 		showImagePreview(url);
 	    return false;
     });

	


     
     $("#slider").slider({
         'min' : 120,
         'max' : 325,
         'value': 120,
         'slide': function(event, ui) {
             var width = (ui.value-10);
             var img_w = width-20;
             $("ul#media li").css("width", width);
             $("ul#media li").css("height", width);
             $(".img").css("height", img_w);

             $("ul#media li .small_thumbnail").css("max-height", img_w);
             $("ul#media li .small_thumbnail").css("max-width", width);

             $.cookie("thumb_width", ui.value, { expires: 10, path: '/' });

			 if(img_w > 90){
				changePreview();
			}
         }
     });

     $("ul#media li").css("width", width);
     $("ul#media li").css("height", width);
     $(".img").css("height", img_w); 
     $("#slider").slider('option', 'value', thumb_width);
     $("ul#media li .small_thumbnail").css("max-height", img_w);
     $("ul#media li .small_thumbnail").css("max-width", width);
	 if(img_w > 90){
		changePreview();
	}
     
     $(".img").mouseenter(function (){
        var bodyWidth = $("body").innerWidth();
        var plus =  $(window).scrollTop();
        var bodyHeight = $("body").innerHeight() + plus;
        var pos = $(this).offset();
        var id = $(this).attr("alt");
        var width = $(this).innerWidth();
        var height = $(this).innerHeight();
        var src = $("img[alt='"+id+"']").attr("src");

	
		
        var footerHeight = $("#lightboxBarBottom").height() + $("#footer").height();;
        if(width < 260){
            $("#imagepreview").html("<img src='"+src+"' />");
				if(img_w == 90){
					if($("img[alt='"+id+"']").width() > $("img[alt='"+id+"']").height()){
						$('#imagepreview img').css({'width': '320px'});
					}else{
						$('#imagepreview img').css({'height': '320px'});
					}

				}
            var previewWidth = $("#imagepreview").innerWidth();
            var previewHeight = $("#imagepreview").innerHeight();
            var finalLeft = pos.left + width + 10;
            var totalLeft = pos.left + width + previewWidth;
            var totalTop = pos.top + footerHeight + previewHeight;
            var finalTop = pos.top;
            if(totalTop > bodyHeight){
               var finalTop = pos.top - previewHeight + height + 40;
            }
            if(totalLeft > bodyWidth){
                var finalLeft = pos.left - previewWidth - 12;
            }
            
            $("#imagepreview").css({"top": finalTop+"px", "left": finalLeft+"px", "display": "block"});
			if(img_w == 90){
				var img = new Image();
				$(img).load(function () {
					$('#imagepreview img').remove();
					$('#imagepreview').append(this);
				}).error(function () {}).attr('src', $("img[alt='"+id+"']").attr("cbx:larger"));
	}

        }
     });
     $(".img").mouseleave(function (){
        $("#imagepreview").css("display","none");
    });
     
});

/**
 * Preview Dialog
 */
function showImagePreview(url) {
    var dialog = $('#preview_dialog').dialog({
        autoOpen: false,
        modal: true,
        zIndex: 10000,
        minHeight: 550,
		width: 780,
		resizable: false,
		dialogClass: 'dialog'
    });
    $(dialog).html("<div style='text-align: center; margin-top: 10px;'><img src='/gfx/cart/ajax-loader.gif' /></div>");
    $(dialog).dialog('open');
    $('.ui-widget-overlay').click(function(){
    	$(dialog).dialog('close');
    });
    $(dialog).load(url);
}

$(document).ready(function(){ 
    
$(".startcenter_category .thumb_trash").live('click', function(){ 
        fader =    $(this).parent();
	//	id  =   $(this).attr('href').split("/id/");


        $.ajax({
            type: "POST",
            url: $(this).attr('href'),
            dataType: 'json',
            success: function(msg){
                fader.fadeOut();


				$('li#cat_id_'+msg.cat_id+' .thumb_categoryAdded').addClass('thumb_category');
				$('li#cat_id_'+msg.cat_id+' .thumb_categoryAdded').removeClass('thumb_categoryAdded');
				
					if(msg.count <= 5){
						$('.more_cats').hide();
					}
            }
        });   
        return false;
    });
    
    
    
    
    var message = new Array(); 
    message['dk'] = "Jeg &oslash;nsker muligheden at kunne bruge professionelt materiale til mine opgaver.<br />Derfor vil jeg gerne anbefale min skole at tilmelde sig colourbox' gratis skoleprogram.<br />For at gennemf&oslash;re en ans&oslash;gning, klik p&aring; linket herunder."; 
    message['de'] = "Ich m&ouml;chte die M&ouml;glichkeit nutzen, professionelles Bildmaterial f&uuml;r meine Schularbeiten zu verwenden.<br>Daher m&ouml;chte ich meine Schule bitten, an Colourbox' kostenfreien Programm f&uuml;r Schulen teilzunehmen.<br>Um die Anfrage zu beenden klicken Sie auf untenstehenden Link:"; 
    message['en'] = "I would like the opportunity to use professional material for my assignments.<br />Therefore I would like to recommend my school to take part in colourbox free-of-charge school program.<br />To complete an application click on below link:";
    $("#lang").change(function() { 
        var message_index 
        message_index = $("#lang").val();
        $("#message_display").empty(); 
        if(message_index == 'dk' || message_index == 'de' || message_index == 'en'){
            $("#message_display").append(message[message_index]); 
        } else{
            $("#message_display").append(message['en']); 
        }
    }); 
});

$(document).ready(function(){
	$("#index_newsmail_signup").click(function () {
		if($('#index_newsmail_email').val() == "") {
			return false;
		}
		var email = $("#index_newsmail_email").val();
		$("#index_newsmail_response").load("/index/newsmailsignup/email/"+email);
		return false;
	});
});

/**
 * Search
 */
$(document).ready(function(){
    var $didyoufind = $('#didyoufind_dialog');

    $("select[name = 'language']").change(function(){
        if ($.cookie("autocomplete") != "0") {
            autocompleteBtn(true);
        }
    });
     
     $("#didyoufind_negative").click(function () {
     	$("#didyoufind_response").load($(this).attr("href"));
     	
         $didyoufind.dialog({
             modal: true,
             height: 325,
				width: 425,
				resizable: false,
				dialogClass: 'dialog'
             });
         $didyoufind.dialog('open');

         $('#didyoufind_comment').select();
         return false;
     });
     
     $("#didyoufind_positive").click(function () {
			$("#didyoufind_response").load($(this).attr("href"));
			return false;
     });

     $("#didyoufind_close").click(function () {
     	$didyoufind.dialog('close');
		return false;
     });
        
		$("#didyoufind_submit").click(function () {
			if($('#didyoufind_comment').val() == $('#didyoufind_comment').attr("title")){
				return false;	
			}			
			if($('#didyoufind_comment').val() == "") {
				return false;
			}
			
			var term = $("#didyoufind_term").val();
			var comment = $("#didyoufind_comment").val();
			
			var dataString = 'q='+ term + '&comment=' + comment;
			  
			  $.ajax({
			    type: "POST",
			    url: "/search/comment/q/",
			    data: dataString,
			    success: function() {
			      $('#didyoufind_response').html($('#didyoufind_response').attr("title"));
			      $('#didyoufind_submitter').css("display","none");
			      $('#didyoufind_text').css("display","none");
			      $('#didyoufind_closer').css("display", "block");
			      $('#didyoufind_comment').css("display", "none");
			      $('#didyoufind_appreciate').css("display", "block");
			    }
			  });

			  return false;

     });
     
     if ($.cookie("autocomplete") != "0") {
	    $("#search_string").autocomplete("/autocomplete/", {
            extraParams: {lang: function() { return $("select[name = 'language']").val(); }},
            cacheLength: 1,
            width: 200,
            minChars: 2,
            max: 20,
            scroll: true,
            scrollHeight: 200,
            multiple: true,
            multipleSeparator: " ",
            selectFirst: false,
            useKeyValueURL: true
        });
    }

   	$("#search_string").click(function () { 
         if($(this).val() == $(this).attr("title"))
         {
				$(this).val("");
         }
     });
});

function new_tab_search(e) {
    var f = $("#" + e);
    f.attr("target", "_blank");
}

function normal_search(e) {
    var f = $("#" + e);
    f.attr("target", "");
}


function expire_notice(){
	var dialog = $('#expire_notice').dialog({
		autoOpen: false,
        modal: true,
		title: $(this).attr('title'),
        zIndex: 10000,
		width: 420,
      	resizable: false,
		dialogClass: 'dialog'
	});
	
	$(dialog).dialog('open');

	return false;
	
}

function notifysuperuser(){
	$.ajax({
	    type: "POST",
	    url: "/index/notify/",
		dataType: "json",
	    success: function( data ) {
			$('#expire_notice').html('<center>'+data.message+'</center>');
			$.each(data.users, function(i, val){
				$('#expire_notice').append('<center><b>'+val.email+'</b></center>');
			});
			
			$('#expire_notice').append('<br><center><button onclick="closenotice();" class="largebutton">'+data.close+'</button></center>');
		}
	});
	
	return false;
}

function closenotice(){
	$('#expire_notice').dialog('close');
}

function addProduct(item){
	result	=   item.split("-");
	pr_type	=   result[0];
	id      =   result[1];

	$.ajax({
		type: "POST",
		url: "/cart/product",
		data: "id="+id+"&type="+pr_type,
		success: function(msg){
			window.location.replace('/cart');
		}
	});
}


function addCategory(item, button){
	var item_id = item[0].id.substring(7);
	$.ajax({
		type: "POST",
		url: "/category/add",
		data: "id="+item_id,
		dataType: 'json',
		success: function(msg){

			if(msg.result == 'added'){
				button.removeClass('thumb_category');
				button.addClass('thumb_categoryAdded');
				$('#category_container').prepend('<div class="startcenter_category" id="startcenter_category_'+msg.cat_id+'"><a href="/category/add/id/'+msg.cat_id+'" class="thumbnail_icons thumb_trash" style="margin-left:0;margin-right:15px;">-</a><a href="/category/index/id/'+msg.cat_id+'/'+msg.cat_name+'">'+msg.cat_name+'</a></div>')
				button.parent().parent().find('.img').prepend('<div class="category_msg">'+msg.message+'</div>'); 
				$('.category_msg').slideDown();
				setTimeout(function(){
					button.parent().parent().find('.category_msg').slideUp("normal", function() { 
						$(this).remove(); 
					});
				},2000);

				if(msg.count > 5){
					$('.more_cats').show();
				}
			}
			if(msg.result == 'removed'){
				button.removeClass('thumb_categoryAdded');
				button.addClass('thumb_category');
				$('#startcenter_category_'+msg.cat_id).remove();
				button.parent().parent().find('.img').prepend('<div class="category_msg">'+msg.message+'</div>'); 
				$('.category_msg').slideDown();
				setTimeout(function(){
					button.parent().parent().find('.category_msg').slideUp("normal", function() { 
						$(this).remove(); 
					});
				},2000);
				if(msg.count <= 5){
					$('.more_cats').hide();
				}
			}
		}
	});
}

function changePreview(){
	$.each($('.img img'), function(i, val){
		if($(val).width() <= 110){
			$(val).attr('src', $(val).attr('cbx:larger'));
		}
	});
}

/**
 * Searchbar
 */
$(function() {
    $("#search_tab a").click(function() {
        var div = $("#search");
        if ($(div).is(":visible")) {
            return false;
        }
        $("#categories_tab").removeClass("active");
        $("#search_tab").addClass("active");
        var text = $(this).text();
        $(this).parent().html(text);
        $(div).show();
        return false;
    });
});
var username_timeout = undefined;
var signup;
var login;

$(document).ready(function(){
	signup = $('#signup_dialog');
	login = $('#login_dialog');
	
	$("#signup_button").click(function () {
        openSignup();
        return false;
    });
    
    $("#signup_close").click(function () {
    	signup.dialog('close');
    	resetSignup();
        return false;
    });

	
	$("#signup_container #alreadyamember-link").click(function(){
		signup.dialog('close');
		openLogin();
		return false;
	});

    $("#signup_dialog form").submit(function(){
        $('.dialog_error').remove();
        $('#dialog_error_top').remove();
        $.ajax({
            type: 'POST',
            data: $(this).serialize(),
            url: $(this).attr('action'),
            dataType: 'json',
            cache: false,
            success: function(data) {
                $.each(data, function(str, val){
                    if(str == 'error'){
                        $.each(val, function(errorType, value){
                            if(errorType == 'username'){
                                if(data.error.username.isEmpty){
                                	$("#signup_username_text").css("display","none");
                                	$("#signup_dialog #signup_username_fail").html('<img class="signup_avail" src="/gfx/dialog/notAvail.png"/>'+data.error.username.isEmpty);
                                	$("#signup_dialog #signup_username_fail").css("display","block");
                                }
                                else if (data.error.username.stringLengthTooShort){
                                	$("#signup_username_text").css("display","none");
                                	$("#signup_dialog #signup_username_fail").html('<img class="signup_avail" src="/gfx/dialog/notAvail.png"/>'+data.error.username.stringLengthTooShort);
                                	$("#signup_dialog #signup_username_fail").css("display","block");
                                }
                            	
                            }
                            else if(errorType == 'password'){
                            	if (data.error.password.isEmpty){
                            		//$("#signup_dialog form input#password").after('<div class="ui-state-error dialog_error"><span class="ui-icon ui-icon-alert"/>'+data.error.password.isEmpty+'</div>');
                            		$("#signup_password_text").css("display","none");
                                	$("#signup_dialog #signup_password_fail").html('<img class="signup_avail" src="/gfx/dialog/notAvail.png"/>'+data.error.password.isEmpty);
                                	$("#signup_dialog #signup_password_fail").css("display","block");
                            	}
                            	else if (data.error.password.stringLengthTooShort){
                            		//$("#signup_dialog form input#password").after('<div class="ui-state-error dialog_error"><span class="ui-icon ui-icon-alert"/>'+data.error.password.stringLengthTooShort+'</div>');
                            		$("#signup_password_text").css("display","none");
                                	$("#signup_dialog #signup_password_fail").html('<img class="signup_avail" src="/gfx/dialog/notAvail.png"/>'+data.error.password.stringLengthTooShort);
                                	$("#signup_dialog #signup_password_fail").css("display","block");
                            	}
                            }
                            else if(errorType == 'email'){
                                if (data.error.email.isEmpty){
                                	//$("#signup_dialog form input#email").after('<div class="ui-state-error dialog_error"><span class="ui-icon ui-icon-alert"/>'+data.error.email.isEmpty+'</div>');
                                	$("#signup_email_text").css("display","none");
                                	$("#signup_dialog #signup_email_fail").html('<img class="signup_avail" src="/gfx/dialog/notAvail.png"/>'+data.error.email.isEmpty);
                                	$("#signup_dialog #signup_email_fail").css("display","block");
                                }
                                else if (data.error.email.emailAddressInvalidFormat){
                                	//$("#signup_dialog form input#email").after('<div class="ui-state-error dialog_error"><span class="ui-icon ui-icon-alert"/>'+data.error.email.emailAddressInvalidFormat+'</div>');
                                	$("#signup_email_text").css("display","none");
                                	$("#signup_dialog #signup_email_fail").html('<img class="signup_avail" src="/gfx/dialog/notAvail.png"/>'+data.error.email.emailAddressInvalidFormat);
                                	$("#signup_dialog #signup_email_fail").css("display","block");
                                }
                            }
							 else if(errorType == 'company'){
	                                
	                                if (data.error.company.stringLengthTooShort){
	                                	//$("#signup_dialog form input#email").after('<div class="ui-state-error dialog_error"><span class="ui-icon ui-icon-alert"/>'+data.error.email.emailAddressInvalidFormat+'</div>');
	                                	$("#signup_company_text").css("display","none");
	                                	$("#signup_dialog #signup_company_fail").html('<img class="signup_avail" src="/gfx/dialog/notAvail.png"/>'+data.error.company.stringLengthTooShort);
	                                	$("#signup_dialog #signup_company_fail").css("display","block");
	                                }
	                            }
                            else if(errorType == 'password_confirm'){
                                //$("#signup_dialog form input#password_confirm").after('<div class="ui-state-error dialog_error"><span class="ui-icon ui-icon-alert"/>'+data.error.password_confirm.noMatch+'</div>');
                            	$("#signup_password_confirm_text").css("display","none");
                            	$("#signup_dialog #signup_password_confirm_fail").html('<img class="signup_avail" src="/gfx/dialog/notAvail.png"/>'+data.error.password_confirm.noMatch);
                            	$("#signup_dialog #signup_password_confirm_fail").css("display","block");
                            }
                            else{
                                $("#login_dialog").prepend('<div id="dialog_error_top"><span class="ui-icon ui-icon-alert"/>'+value+'</div>');
                            } 
                        })
                    }
                });
                
                if(data == "SUCCESS"){
                	
                	$("#signup_container").css("display","none");
                	$("#signup_success").css("display","block");
                }
                
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $("#login_dialog").prepend('<div id="dialog_error_top"><span class="ui-icon ui-icon-alert"/>An error has ocurred, please try again, or contact colourbox on <a href="mailto:info@colourbox.com">info@colourbox.com</a<</div>');
            }
        });
        return false
    });
	
	
    $('#submit_signup').click(function () {
        $("#chk").val("1");
    });
    
    $("#signup_dialog input[name='username']").after('<br><div id="err_usrname" class="err_usrname"><span id="txt"></span></div>');
    
	
  	$("#signup_suggestions a").click(function(){
		$("#err_usrname").toggle();
		return false;
	});

//Quick Signup

    $("#signup_dialog input[name='username']").keyup(function(){
      //  $("#err_usrname .icon").removeClass('found');
      //  $("#err_usrname .icon").removeClass('notfound');
        if(username_timeout != undefined) {
            clearTimeout(username_timeout);
        }
        var form_username = $(this);
        if($(this).val().length < 5){
            $("#err_usrname").hide();
        }
        else{
        //    $("#err_usrname").show();
            
          //  $("#err_usrname #txt").html('Checking if username is available');
            username_timeout = setTimeout(function() {
				checkUsername(form_username.val());
            }, 1000);
        }
    });
});


                                                                              

function alternatetousername(){
    $("#err_usrname #txt a").click(function(){
    
        $text = $(this).text();
        $("#signup_dialog input[name='username']").val($text);
        $("#err_usrname").fadeOut();
		checkUsername($(this).text())
            
        return false;
    });
}

function checkUsername(username){
	split_email =  $("#signup_dialog input[name='email']").val();
	$.ajax({
        type: 'POST',
        data: ({
            'username': username,
            'full_name': split_email.replace('@', ' ').split('.', 1),
            'email': $("#signup_dialog input[name='email']").val()
        }),
        url: '/signup/checkusername/',
        dataType: 'json',
        cache: false,
        success: function(data) {
            if(data.error){
                $("#err_usrname .icon").addClass('notfound');
                $("#err_usrname #txt").html(data.error);
                $("#err_usrname .icon").removeClass('found');
            }
            else{
                if(data.username != 0){
                    $.each(data.usernames, function(str, val){
                        $("#err_usrname #txt").append('<a href="">'+val+'</a><br />');
                    });
                    $("#err_usrname .icon").removeClass('found');
						$("#signup_dialog #signup_username_fail").css("display","none");
						$("#signup_username_text").css("display","none");
						$("#signup_username_chk_success").css("display","none");
						$("#signup_username_chk_fail").css("display","block");
						$("#signup_suggestions").css("display", "block");
                    	alternatetousername();
                }
                else{
				
						$("#signup_dialog #signup_username_fail").css("display","none");
						$("#signup_username_text").css("display","none");
						$("#signup_username_chk_fail").css("display","none");
						$("#signup_suggestions").css("display", "none");
						$("#signup_username_chk_success").css("display","block");
                }
            }
        }
    });
}


function openSignup() {
	signup.dialog({
        modal: true,
		width: 455,
		resizable: false,
		dialogClass: 'dialog'
        });
    signup.dialog('open');


    return false;
}

function openLogin() {
      login.dialog({
            modal: true,
            /*height: 245,*/
			width: 355,
			resizable: false,
			dialogClass: 'dialog'
            });
        login.dialog('open');
        
        return false;

}


function resetSignup() {

	// Reset the form
	$("#signup_container").css("display","block");
	$("#signup_success").css("display","none");
	
	$("#signup_container #username").val("");
	$("#signup_container #company").val("");
	$("#signup_container #email").val("");
	$("#signup_container #password").val("");
	$("#signup_container #password_confirm").val("");
	$('#signup_container #newsmail-zulubox').attr('checked', false);

	
	$("#signup_container #signup_username_chk_success").css("display","none");
	$("#signup_container #signup_username_chk_fail").css("display","none");
	$("#signup_container #signup_username_fail").css("display","none");
	$("#signup_container #signup_password_fail").css("display","none");
	$("#signup_container #signup_password_confirm_fail").css("display","none");
	$("#signup_container #signup_email_fail").css("display","none");
	
	$("#signup_container #signup_username_text").css("display","block");
	$("#signup_container #signup_password_text").css("display","block");
	$("#signup_container #signup_password_confirm_text").css("display","block");
	$("#signup_container #signup_email_text").css("display","block");
	$("#signup_container #signup_username_text").css("display","block");
	
}

 $(document).ready(function(){
    $("#startcenter_open").click(function(event) {
        if ($("#startcenter_content").is(":hidden")) { 
        	$("#startcenter_content").slideDown();
            $("#startcenter_login").fadeOut();
            //$('#test1').jGrowl("You have just opened the startcenter.");
            newtext = $("#close_startcenter_text").text();
            $("#startcenter_button").text(newtext); 
            $('#startcenter_arrow').attr("src","/gfx/defaults/account/lightbox/pilop.png");
        }
        else{
        	$("#startcenter_content").slideUp();
            $("#startcenter_login").fadeIn();
            newtext = $("#open_startcenter_text").text();
            $("#startcenter_button").text(newtext);
            $('#startcenter_arrow').attr("src","/gfx/defaults/account/lightbox/pil.png");
        }
     })
     
     $("#startcenter_content #newsmail_switch").change(function(event) {
    	 $.ajax({
    	        url: "/startcenter/newsmail",
    	        cache: false,
    	        success: function(response){
    	        }
    	    });
     })
  $("#startcenter_content #preview_switch").change(function(event) {
    	 $.ajax({
    	        url: "/startcenter/preview",
    	        cache: false,
    	        success: function(response){
	 				window.location.reload();
    	        }
    	    });
     })
      
     // for user logged in
     $("#startcenter_content #autocomplete_switch").change(function(event) {
         $.ajax({
             url: "/startcenter/autocomplete",
             cache: false,
             success: function(response){
                autocompleteBtn(response);
                window.location.reload();
            } 
         })
      });
      /* Change language */
     $("#language_selector .languageflags").click(function(event) {
    	 lang = $(this).attr("id");
    	 changelanguage(lang);
     })
     
     /* Change language */
     $("#startcenter_languageradio input:radio").click(function(event) {
    	 lang = $(this).val();
    	 changelanguage(lang);
     })
     
     function changelanguage(lang){    	
   	 $.cookie("language", lang, { path: '/', expires: 365 });
   	 $.ajax({
   		  type: "GET",
   		  cache: false,
   		  url: "/index/changelanguage/lang/"+lang
   		});
   	 $("#language_selector").ajaxSuccess(function(evt, request, settings){
   		   location.reload();
   		 });
    }
          
 });

 function autocompleteBtn(bool){
    if(bool == 'false'){
        $("#search_string").unautocomplete();
        $("#search_string").removeClass();
        $('#autocomplete_switch').attr('checked', false);
        

        return;
    }
    
    $("#search_string").autocomplete("/autocomplete/", {
        extraParams: {timestamp: 0, lang: function() { return $("select[name = 'language']").val(); }},
        cacheLenght: 1,
        width: 200,
        max: 20,
        scroll: true,
        selectFirst:false,
        scrollHeight: 200,
        multiple: true,
        multipleSeparator: " ",
        useKeyValueURL: true
    });
    $('#autocomplete_switch').attr('checked', true);
    return;
 }
var $download_box;
var $lightbox;
$(function() {
    $lightbox = $('#lightboxContainer'), $media = $('#media'), $containment = $('#lightboxMedias');
    $download_box = $("#download_box");
    
    var options = { path: '/'};
    
    lb_img_prw();
    lightbox_container();
    lightbox_draggable();

	$('.lightbox_delete').click(function(){
		var deleted = confirm($(this).attr('alt'));
		var test = $(this).parent().parent().parent();
		
		if(deleted){
		    $.ajax({
		        type: 'POST',
		        url: $(this).attr('href'),
		        dataType: 'json',
		        success: function(response) {
					test.fadeOut();
				}
		    });
			return false;			
		}else{
			return false;	
		}
	});


    $(".toggle_lightbox").click(function() {
        if ($("#lightboxContent").is(":visible")) {
            $("#lightboxContent").slideUp("slow");
            $("#minimize_lightbox").removeClass('close_lightbox');
            $("#minimize_lightbox").addClass('open_lightbox');
            $("#lightboxArrow").removeClass('lightboxArrowClose');
            $("#lightboxArrow").addClass('lightboxArrowOpen');
            $("#lightboxContent-fill").hide();
            $.cookie('showLightbox', 'expanded', options);
            return false;
        } else {
            $("#lightboxContent").slideDown("slow");
            $.cookie('showLightbox', 'collapsed', options);
            $("#minimize_lightbox").removeClass('open_lightbox');
            $("#minimize_lightbox").addClass('close_lightbox');
            $("#lightboxArrow").removeClass('lightboxArrowOpen');
            $("#lightboxArrow").addClass('lightboxArrowClose');
            $("#lightboxContent-fill").show();
            return false;
        }
    });

    var showLightbox = $.cookie('showLightbox');
    if (showLightbox == 'collapsed') {
        $("#lightboxContent").show();
        $("#minimize_lightbox").removeClass('open_lightbox');
        $("#minimize_lightbox").addClass('close_lightbox');
        $("#lightboxArrow").removeClass('lightboxArrowOpen');
        $("#lightboxArrow").addClass('lightboxArrowClose');
        $("#lightboxContent-fill").show();
    }

    $("#select_lightbox").change(function() {
        this.submit();
    });

    // Fade in and out lightbox create in account/lightbox
    $("#new_lightbox").click(function(){
        if ($("#new_lightbox_form").is(":visible")){ $("#new_lightbox_form").fadeOut(); } 
        else {$("#new_lightbox_form").fadeIn();}
    });

    // let the media items be draggable
    $('li.drag',$media).draggable({
        cancel: 'div.thumb_menu',// clicking an icon won't initiate dragging
        revert: 'invalid', // when not dropped, the item will revert back to its initial position
        containment: 'document', // stick to demo-frame if present
        helper: 'clone',
        cursor: 'move',
        start: function(ev, ui){
            $(this).find('div.imagepreview').hide();
            $(ui.helper).find('div.imagepreview').remove();
        }
    });

    // let the lightbox be droppable, accepting the media items
    $('#content').droppable({
        accept: '#lightboxContainer > li',
        drop: function(ev, ui) {
            deleteImage(ui.draggable);
            $item_id = ui.draggable[0].id.substring(9);
            removeLightboxIndicator($item_id);
        }
    }); 

    // let the lightbox be droppable, accepting the media items
    $lightbox.droppable({
        accept: '#media > li',
        activeClass: 'active_lightbox',
        drop: function(ev, ui) {
            saveImage(ui.draggable);
            $item_id = ui.draggable[0].id.substring(9);
            addLightboxIndicator($item_id);
        }
    });
    
    
    
    $('ul#media > li').click(function(ev) {
        var $item = $(this);
        var $target = $(ev.target);
        if ($target.is('a.thumb_lightbox')) {    
            saveImage($item);
            $item_id = $item.attr('id').substring(9);
            addLightboxIndicator($item_id);
			return false;
        } 
        else if ($target.is('a.thumb_trash')) {
            deleteImage($item);
			return false;
        } 
        else if ($target.is('a.thumb_trash_lb')) {
            return false;
        } 
        else if ($target.is('a.thumb_cart')) {
            insertCart($item);
			return false;
        } 
        else if ($target.is('a.thumb_download')) {
            return true;
        }
		else if ($target.is('a.thumb_set')){
			return true;
		}
		else if ($target.is('a.thumb_category')){
			addCategory($item, $target);
			return false;
		}
		else if ($target.is('a.thumb_categoryAdded')){
				addCategory($item, $target);
			return false;
		}
   //     return false;
    });
    
        
    
    $('ul#media > li').mouseout(function(ev) {
        var $target = $(ev.target);
        if ($target.is('img')) {
            var title = $target.attr('alt');
            $('#imagepreviewer_'+title).hide();
        }
        return false;
    });
       
    $('#create_new_lightbox').click(function(ev){
        var title = $('#create_new_lightbox').attr('title');
        var $modal = $('#lightbox_dialog');
        $modal.dialog({title: title, modal: true, width: 335, resizable: false, dialogClass: 'dialog' });
        $modal.dialog('open');
    });
    
    $('#share_lightbox').click(function(ev) {
        var title = $('#share_lightbox').attr('title');
        var $modal = $('#share_lightbox_dialog');
        $modal.dialog({title: title, modal: true, resizable: true, width: 400, height: 210, dialogClass: 'dialog' });
        $modal.dialog('open')
    });

});

function saveImage($item) {
    $item_id = $item[0].id.substring(9);
    var post_data = {media_id: $item[0].id};
    //var $thumb = $('#'+$item[0].id+' .img img').attr('src');
    var checkAllowed = $('#'+$item[0].id+' .thumb_download').attr('title');
    $.ajax({
        type: 'POST',
        url: "/account/lightbox/lbox",
        data: post_data,
        dataType: 'json',
        success: function(response) {
            if (response[2]) {
                $lightbox.prepend('<li id="'+$item[0].id+'"></li>');
                $new_item = $('#'+$item[0].id);
                $new_item.addClass('media_lightbox');
                $new_item.append('<div class="lightbox_img_div"><img class="lb_img_prw" href="/search/media/id/'+$item_id+'" src="'+response[2]+'" alt="'+$item_id+'" /></div>');
                $new_item.append('<a href="/account/lightbox/deleteimage/media_id/'+$item_id+'" title="Delete this image" class="white_icons trash">Delete image</a>');

                $cnt_lb_img = $('#cnt_lb_img').html();
                $new_count = (parseInt($cnt_lb_img) + 1);
                $('#cnt_lb_img').html($new_count);
                $('#readyDownload').hide();
                if (checkAllowed) {
                    $new_item.append('<a href="/download/media/id/'+$item_id+'" class=" white_icons small_download">Download</a>');
                } else {
                    $new_item.append('<a href="/cart/add/media/id/'+$item_id+'" class="white_icons small_cart">Add to cart</a>');
                }

                lb_img_prw();
                lightbox_container();
                lightbox_draggable();

            } else {
                var title = "Information";
                $('#test1').html("<div style='text-align: center; margin-top: 30px'><h5>"+response[1]+"</h5></div>");
                $('#test1').dialog({title: title, modal: true, resizable: false, dialogClass: 'dialog' });
                $('#test1').dialog('open');
            }
            lbOrCart()
        }
    });
	console.log($item_id)
    return true;
}

function showDownloadOrCart(downloadOrCart, itemcount){
	if(downloadOrCart > 0 && itemcount > 0){
		$("#download_lightbox").css("display","none");
		$("#add_lightbox_to_cart").css("display","block");
	}else if(downloadOrCart == 0 && itemcount > 0){
		if(itemcount > 100){
			$("#download_lightbox").css("display","none");
			
		}else{
			$("#download_lightbox").css("display","block");
			
		}
		$("#add_lightbox_to_cart").css("display","none");
	}else{
		$("#download_lightbox").css("display","none");
		$("#add_lightbox_to_cart").css("display","none");
	}
}

function deleteImage($item, $where) {
    $item_id = $item[0].id;
    if ($where == 1) {
        $new_item_id = $item[0].id;
        $item_id = $new_item_id.substring(3);
    }
    removeLightboxIndicator($item_id.substring(9));
    $.post("/account/lightbox/lboxrm", {
        "media_id": $item_id
    }, function(response) {
        if (response == '"DELETED!"') {
            $item.fadeOut(function() {
                $item.remove();
            });
            $cnt_lb_img = $('#cnt_lb_img').html();
                $new_count = (parseInt($cnt_lb_img) - 1);
                $('#cnt_lb_img').html($new_count);
                $('#readyDownload').hide();
        } else {}
        lbOrCart()
    });
}

function truebody(){
    return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

var lightboxIsDownloaded = false;

function setDownloadCookie(lightbox_id) {
    var title = $download_box.attr('title');
    $.cookie('download_lightbox', lightbox_id, {path: '/'});
    var url =  '/account/lightbox/download/lb_id/'+lightbox_id;
    var dialog = $download_box.dialog({modal: true, width: 500, resizable: false, dialogClass: 'dialog'});
    $(dialog).html("<div style='text-align: center; margin-top: 10px;'><img src='/gfx/cart/ajax-loader.gif' /></div>");
    $(dialog).dialog('open');
    $(dialog).load(url);
}
   
function addLightboxToCart(){
    $.ajax({
        url: "/account/lightbox/lbtocart",
        cache: false,
        success: function(response){
            var myObject = eval('(' + response + ')');
            for (i=0;i<myObject.length;i++) {
                if (!(myObject[i].allowDownload)) {
                    insertLightboxCart(myObject[i].media_id, myObject[i].thumbnail);
	        	}	            	
	        };
	   	}
    });
}

function addLightboxIndicator(id){
	$("#indicator_"+id).addClass("lightboxindicatorOn");
}

function removeLightboxIndicator(id){
	$("#indicator_"+id).removeClass("lightboxindicatorOn");
}

function rm_lb_image($media, $lightbox) {
        $.post("/account/lightbox/lboxrm", {
            "media_id": $media,
            "lightbox_id": $lightbox
        } ,
        function(response)
        {
            
            if (response == '"DELETED!"')
            {
                $('#media #media_id_'+$media).fadeOut();
                if($('#lightboxContainer #media_id_'+$media).height() != null){
                    var lb_img_cnt = parseInt($('#cnt_lb_img').text())-1;
                    $('#cnt_lb_img').text(lb_img_cnt);
                }
                $('#lightboxContainer #media_id_'+$media).fadeOut();
                var nrm_lb_img_cnt = parseInt($('#nrm_lb_img_cnt').text())-1;
                $('#nrm_lb_img_cnt').text(nrm_lb_img_cnt);
                $('#readyDownload').hide();
            }
            else
            {
                alert(response);
            } 
        });
    };
    
function lbOrCart(){
    $.ajax({
        url: "/account/lightbox/lbtocart",
        cache: false,
        success: function(response){
            var myObject = eval('(' + response + ')');
            var downloadOrCart = 0;
            var itemCount = 0;        
            for (i=0;i<myObject.length;i++)
            {
                if(!myObject[i].allowDownload)
                {
                    downloadOrCart++;
                }
                itemCount++;
            };
            showDownloadOrCart(downloadOrCart, itemCount);        
        }
    });
}

function lb_img_prw(){
    $(".lb_img_prw").click(function(){ 
        var url = "/search/media/id/"+$(this).attr("alt");
        showImagePreview(url);
        return false;
    });
}

function lightbox_container(){
    $('ul#lightboxContainer > li').click(function(ev) {
        var $item = $(this);
        var $target = $(ev.target);
        if ($target.is('a.trash')) {
            deleteImage($item);
        } else if ($target.is('a.small_cart')){
            insertCart($item);
        } else if($target.is('a.small_download')){
            return true;
        }
        return false;
    });
}

function lightbox_draggable(){
    $('li', $lightbox).draggable({
        cancel: 'a.white_icons',// clicking an icon won't initiate dragging
        revert: 'invalid', // when not dropped, the item will revert back to its initial position
        containment: 'document', // stick to demo-frame if present
        helper: 'clone',
        zIndex: 9999,
        cursor: 'move'
    });
 }
/* JS for feedback function */

$(document).ready(function(){
	var $support = $('#support_dialog');

	
	//$("#index_smallbox_1")

	
	$("#support_btn").click(function () {
		
        $support.dialog({
            modal: true,
			width: 425,
			close: supportClose,
			resizable: false,
			dialogClass: 'dialog'
            });
        $support.dialog('open')


    });
    
	$("#feedback_btn").click(function () {
			
		$support.dialog({
            modal: true,
			width: 425,
			close: supportClose,
			resizable: false,
			dialogClass: 'dialog'
            });
        $support.dialog('open')

    });
	
	$("#index_smallbox_1").click(function () {
		
/*		$support.dialog({
            modal: true,
			width: 425,
			close: supportClose,
			resizable: false,
			dialogClass: 'dialog'
            });
        $support.dialog('open')

*/
		window.location.replace('http://www.zulubox.com');

    });
	
    $("#support_close").click(function () {

    	$support.dialog('close');
    	return false;
    });
    
    function supportClose(){
    	
    	$('#support_submitter').css("display","block");
	    $('#support_text').css("display","block");
	    $('#support_comment').css("display", "block");
	    $('#support_closer').css("display", "none");
	    $('#support_appreciate').css("display", "none");
	    $('#support_comment').val("");
	    $('#support_email').css("display","block");
	    $('#support_subject').css("display","block");
	    $('#support_reciever').css("display","block");
    }
   
    
	$("#support_submit").click(function () {
		
		var comment = $("#support_comment").val();
		var email = $("#support_email").val();
		var subject = $("#support_subject").val();
		var reciever = $("#support_reciever").val();
		
		if(comment == "") {
			return false;
		}
		if(email == "") {
			return false;
		}
		if(subject == "") {
			return false;
		}
		
		var dataString = 'comment='+comment+'&email='+email+'&subject='+subject+'&reciever='+reciever;
		  
		  $.ajax({
		    type: "POST",
		    url: "/index/support/",
		    data: dataString,
		    success: function() {
			  $('#support_submitter').css("display","none");
		      $('#support_text').css("display","none");
		      $('#support_closer').css("display", "block");
		      $('#support_comment').css("display", "none");
		      $('#support_appreciate').css("display", "block");
		      $('#support_email').css("display","none");
			  $('#support_subject').css("display","none");
			  $('#support_reciever').css("display","none");
		    }
		  });
		  
		  return false;

    });
	
});
/* JS for Cart */
var options = { path: '/'}; 

$(function(){
    $('#products_box input').click(function(){

        var item    =   $(this).attr('id');
        result  =   item.split("-");
        type    =   result[0];
        id      =   result[1];
        $.ajax({
            type: "POST",
            url: "/cart/product",
            data: "id="+id+"&type="+type,
            success: function(msg){
                if(type != 'prepaidcard'){
                    if($("#basket_dropdown #cart_license").size() == 1){
                        $("#cart_license").remove();
                    }
                    $("#basket_dropdown").prepend("<div class='cart_select' id='cart_license'><div class='cart_image_container'><img class='cart_image' alt='Image' src='/gfx/cart/license_"+id+".png' /></div><div class='cart_text'>"+type+"</div><div class='cart_remove_container'><img src='/gfx/search/minus.png' class='cart_remove_btn' onclick=\"javascript:remove_cookie('license_"+id+"');\" /></div></div><div class='clear'></div>");
                }
                else {
                    $("#cart_credits").remove();
                    $("#basket_dropdown").prepend("<div class='cart_select' id='cart_credits'><div class='cart_image_container'><img class='cart_image' alt='Image' src='/gfx/cart/80x80-credits.png' /></div><div class='cart_text'>100 credits</div><div class='cart_remove_container'><img src='/gfx/search/minus.png' class='cart_remove_btn' onclick=\"javascript:remove_cookie('credits');\" /></div></div><div class='clear'></div>");
                }
                i = $("#basket_dropdown .cart_select").size();
                $("#item_count").text(i);
            }
        });
    });

    if($('#total_amount').text() >= 100){
        $('#sub_total').show()
    }

    /* When mousing over div id 'front_basket' */
    $("#front_basket").mouseover(function(){
        /* get content from php */
        i = $("#basket_dropdown .cart_select").size();
        if(i != 0){
            $("#basket_dropdown").css('display', 'block');
        }
    });

    $("#basket_dropdown").mouseleave(function(){
        $("#basket_dropdown").css('display','none');
    });
});


//inserting item into cart
function insertCart($item){
    var $item_id = $item[0].id.substring(9);
    var $thumb = $('#'+$item[0].id+' .img img').attr('src');
            $.post("/cart/add", {
                "id": $item_id
            } ,
            function(response){
                if(response > 0)
                {
                    var cart_id = "cart_"+$item_id; 
                    $('#'+$item[0].id).effect("pulsate", {times: 1});
                    /* appending a div with the cookie ind div id basket_dropdown */
                    $("#basket_dropdown").prepend("<div class='cart_select'  id='"+cart_id+"'><div class='cart_image_container'><img class='cart_image' alt='Image' src='"+$thumb+"' /></div><div class='cart_text'>Item no. "+$item_id+"</div><div class='cart_remove_container'><img src='/gfx/search/minus.png' class='cart_remove_btn' onclick='javascript:remove_cookie(\"image_"+$item_id+"\");' /></div></div><div class='clear'></div>");
                    $("#cart_"+$item_id).fadeIn();
                    i = $("#basket_dropdown .cart_select").size();
                    $("#item_count").text(i);
                    
                }
            });
            var cart_id = "cart_"+$item_id; 
   
    return true;
};

function insertLightboxCart(item_id, thumb){
	
            $.post("/cart/add", {
                "id": item_id
            } ,
            function(response){
                if(response)
                {
                    var cart_id = "cart_"+item_id; 
                    $('#media_id_'+item_id).effect("pulsate", {times: 1});
                    /* appending a div with the cookie ind div id basket_dropdown */
                    
                    $("#basket_dropdown").prepend("<div class='cart_select'  id='"+cart_id+"'><div class='cart_image_container'><img class='cart_image' alt='Image' src='"+thumb+"' /></div><div class='cart_text'>Item no. "+item_id+"</div><div class='cart_remove_container'><img src='/gfx/search/minus.png' class='cart_remove_btn' onclick='javascript:remove_cookie(\"image_"+item_id+"\");' /></div></div><div class='clear'></div>");
                    i = $("#basket_dropdown .cart_select").size();
                    $("#item_count").text(i);
                }
            });
    var cart_id = "cart_"+item_id; 
}

/* Removing specific cookie */
function remove_cookie(item){
	
	result 	 = 	item.split("_");
	type 	 = 	result[0];
	id 	 	 = 	result[1];
	
	if(type == 'credits'){
		$.ajax({
			  type: "GET",
			  url: "/cart/remove/pr/Credits"
			});
	    $("#cart_credits").remove(); //removing the div with the cookie
	}
	else if(type == 'license'){
		$.ajax({
			  type: "GET",
			  url: "/cart/remove/id/"+id+"/pr/License"
			});
		$("#cart_license").remove(); //removing the div with the cookie
	}
	else {
		$.ajax({
			  type: "GET",
			  url: "/cart/remove/id/"+id+"/pr/Cart"
			});
	    $("#cart_"+id).remove(); //removing the div with the cookie
	}
    i = $("#basket_dropdown .cart_select").size();
    $("#item_count").html('<span id="item_count">'+i+'</span>')
    if(i == 0){
    	$("#basket_dropdown").css('display','none');
    }
};

/** Shopping Basket **/
$(function() {
    
    $("#shoppingcart .description .credits .controls .decrease") .click(function() {
        var total_price = $('#total_price').text();
        var tr = $(this).parents("tr");
        var total_credits = $('#total_amount').text();
            $.post(
                "/cart/credits", {
                "id": 'minus',
                "price": total_price,
                "total_credits": total_credits
            } ,
            function(response){
                var myObject = eval('(' + response + ')');
                var amount = myObject.credits;
                if (amount < 1 || amount == 'null') {
                    $(".remove a",tr).click();
                    return;
                }
                
                var myObject = eval('(' + response + ')');
                $(".amount",tr).text(myObject.credits);
                $("#total_amount").text(myObject.count_credits);
                $(".price",tr).text(myObject.currency +' '+ myObject.price);
                $("#totalAmount").text(myObject.currency+' '+myObject.totalprice_vat);
                $("#totalVat").text('('+myObject.currency+' '+myObject.vat+')');
                $("#subtotal").text(myObject.currency+' '+myObject.subtotal);
                $("#discount").text(myObject.currency+' '+myObject.discount);
                $("#total_price").text(myObject.countprice);
                $("#total_price_vat").text(myObject.countprice_vat);
                if(myObject.count_credits < 100){
                    $('#sub_total').hide()
                }
                return;
            });
            
    });
    $("#shoppingcart .description .credits .controls .increase") .click(function() {
        var tr = $(this).parents("tr");
        var total_price = $('#total_price').text();
        var total_credits = $('#total_amount').text();
        $.post("/cart/credits", {
                "id": 'plus',
                "price": total_price,
                "total_credits": total_credits
            } ,
            function(response){
                var myObject = eval('(' + response + ')');
                $(".amount",tr).text(myObject.credits);
                $("#total_amount").text(myObject.count_credits);
                $(".price",tr).text(myObject.currency +' '+ myObject.price);
                $("#totalAmount").text(myObject.currency+' '+myObject.totalprice_vat);
                $("#totalVat").text('('+myObject.currency+' '+myObject.vat+')');
                $("#subtotal").text(myObject.currency+' '+myObject.subtotal);
                $("#discount").text(myObject.currency+' '+myObject.discount);
                $("#total_price").text(myObject.countprice);
                $("#total_price_vat").text(myObject.countprice_vat);
                if(myObject.count_credits >= 100){
                    $('#sub_total').show()
                }
                return;
            });
    });
    
    $("#shoppingcart .remove a") .click(function() {
        var tr = $(this).parents("tr");
        var removing_id = $(this).attr("id");
        var product = $(this).attr("alt");
        
        if(product == 'Credits'){
            $.ajax({
                type: "GET",
                url: "/cart/remove/pr/Credits"
            });
        }
        else{
            $.ajax({
                type: "GET",
                url: "/cart/remove",
                data: {
                    "id": removing_id,
                    "pr": product
                }
            });
        };
        window.location.reload()
        return false;
    });
    
    $("#shoppingcart a.validatebilling") .click(function() {
        $("#shoppingcart form").submit();
        return false;
    });
});

$(document).ready(function(){
    $('.index_all_offers input').click(function(){
        var item    =   $(this).attr('id');
        var credits = $('#total_amount').text();
        result  =   item.split("-");
        type    =   result[0];
        id      =   result[1];
        $.ajax({
            type: "POST",
            url: "/cart/product",
            data: "id="+id+"&type="+type+"&credits="+credits,
            success: function(msg){
                document.location.href = '/cart';
            }
        });
    }); 
    
    $('#click_these span').click(function(){
        var item    =   $(this).attr('id');
        var credits = $('#total_amount').text();
        result  =   item.split("-");
        type    =   result[0];
        id      =   result[1];
        $.ajax({
            type: "POST",
            url: "/cart/product",
            data: "id="+id+"&type="+type+"&credits="+credits,
            success: function(msg){
                document.location.href = '/cart';
            }
        });
    });   

    $('.piggyBtn div').click(function(){
        var item    =   $(this).attr('id');
        var credits = $('#total_amount').text();
        result  =   item.split("-");
        type    =   result[0];
        id      =   result[1];
        $.ajax({
            type: "POST",
            url: "/cart/product",
            data: "id="+id+"&type="+type+"&credits="+credits,
            success: function(msg){
                document.location.href = '/cart';
            }
        });
    });
});


/* JS for feedback function */
$(document).ready(function(){
	var $login = $('#login_dialog');
	
	$("#login_button").click(function () {
        $login.dialog({
            modal: true,
            /*height: 245,*/
			width: 355,
			resizable: false,
			dialogClass: 'dialog'
            });
        $login.dialog('open');
        
        return false;

    });

	$("#supplier_login_button").click(function () {

        $login.dialog({
            modal: true,
            height: 245,
			width: 355,
			resizable: false,
			dialogClass: 'dialog'
            });
        $login.dialog('open');

    });
    
    $("#login_dialog form").submit(function(){
        $('.dialog_error').remove();
        $('#dialog_error_top').remove();
        $.ajax({
            type: 'POST',
            data: $(this).serialize(),
            url: $(this).attr('action'),
            dataType: 'json',
            cache: false,
            success: function(data) {
                $.each(data, function(str, val){
                    if(str == 'error'){
                        $.each(val, function(errorType, value){
                            if(errorType == 'username'){
                                $("#login_dialog form input#username").after('<div class="ui-state-error dialog_error"><span class="ui-icon ui-icon-alert"/>'+data.error.username.isEmpty+'</div>');
                            }
                            else if(errorType == 'password'){
                                $("#login_dialog form input#password").after('<div class="ui-state-error dialog_error"><span class="ui-icon ui-icon-alert"/>'+data.error.password.isEmpty+'</div>');
                            }
                            else{
                                $("#login_dialog").prepend('<div id="dialog_error_top"><span class="ui-icon ui-icon-alert"/>'+value+'</div>');
                            } 
                        })
                    }
                    if(str == 'redirect_url'){
                        $login.dialog('close');
                        window.location.href = val;
                    }
                });
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $("#login_dialog").prepend('<div id="dialog_error_top"><span class="ui-icon ui-icon-alert"/>An error has ocurred, please try again, or contact colourbox on <a href="mailto:info@colourbox.com">info@colourbox.com</a<</div>');
            }
        });
        return false
    });
    
});
$(function(){
	var import_dialog = $('#import_dialog');
	var article_contents = $('#article_contents');
	$(".openfolder").click(function(){
    		var foldername = $(this).attr("href").split("/").pop();
    		getFolderContent(foldername);
    		return false;
      	}
    );
	function getFolderContent(foldername){
		$("#contents_files").html("");
		$.getJSON("/account/supplier/openfolder/folder/"+foldername, function(data){
			$.each(data, function(i,item){
				$("#article_contents #contents_empty").hide();
				$("#article_contents #contents_files").append(item+"<br />");
		    });
		    if($("#article_contents #contents_files").html() == ""){
		    	$("#article_contents #contents_empty").show();
			}
    		article_contents.dialog({
	            modal: true,
				width: 400,
				resizable: false,
				dialogClass: 'dialog'
	        });
    		article_contents.data('title.dialog', foldername);
        	article_contents.dialog('open');
		});
	}
	$(".openlog").toggle(
		function () {
			var id = $(this).attr("href").split("/").pop();
			$(".import_log_opener_"+id).show();
			return false;
		},
		function () {
			var id = $(this).attr("href").split("/").pop();
			$(".import_log_opener_"+id).hide();
			return false;
		}
	);
	$(".import_button").click(function () {
		var file = $(this).attr("href").split("/").pop();
		$("#import_dialog input[name='item']").val(file);
		import_dialog.dialog({
	        modal: true,
			width: 355,
			resizable: false,
			close: import_dialog_close(),
			dialogClass: 'dialog'
	        });
		import_dialog.data('title.dialog', 'Import: '+file);
	    import_dialog.dialog('open');
        return false;
    });
	$("#import_auto").click(function(){
		if($(this).attr('checked')){
			$.get("/account/supplier/setauto/set/true", function(){
				window.location.href = "/account/supplier/import"; 
			});
		}else{
			$.get("/account/supplier/setauto/set/false", function(){
				window.location.href = "/account/supplier/import"; 
			});
		}
	});
    
	$("#import_dialog form").submit(function(){
        $('.dialog_error').remove();
        $('#dialog_error_top').remove();
        $.ajax({
            type: 'POST',
            data: $(this).serialize(),
            url: $(this).attr('action'),
            dataType: 'json',
            cache: false,
            success: function(data) {
                if(data == "IMPORT"){
                	window.location.href = "/account/supplier/import";
                }else{
                	$("#import_dialog").prepend('<div id="dialog_error_top"><span class="ui-icon ui-icon-alert"/>'+data+'</div>');
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $("#import_dialog").append('<div id="dialog_error_top"><span class="ui-icon ui-icon-alert"/>An error has ocurred, please try again, or contact colourbox on <a href="mailto:info@colourbox.com">info@colourbox.com</a></div>');
            }
        });
        return false
    });
	
	$(".supplier_removetestimage").live('click', function(){
	    var url = $(this).attr("href");
		var id = url.split("/").pop();
		$.getJSON(url, function(data) {
			if(data == "true"){
				$("#supplier_testimage_"+id).fadeOut(1000, function(){
					uploadcount = $(".supplier_removetestimage:visible").size();
					if(uploadcount == 5){
						$("#upload_done input").css("display", "block");
						$("#SWFUpload_0").css("display", "none");
					}else{
						$("#upload_done input").css("display", "none");
						$("#SWFUpload_0").css("display", "block");
					}
				});
				var stats = upload1.getStats();
				stats.successful_uploads--;
				upload1.setStats(stats);
			}else{
				alert("Error");
			}
		});
		return false;
	});
    
});
function import_dialog_close(){
	$("#dialog_error_top").hide();
}
/**
 * SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com
 *
 * mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/,  http://www.vinterwebb.se/
 *
 * SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilzén and Mammon Media and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */


/* ******************* */
/* Constructor & Init  */
/* ******************* */
var SWFUpload;

if (SWFUpload == undefined) {
	SWFUpload = function (settings) {
		this.initSWFUpload(settings);
	};
}

SWFUpload.prototype.initSWFUpload = function (settings) {
	try {
		this.customSettings = {};	// A container where developers can place their own settings associated with this instance.
		this.settings = settings;
		this.eventQueue = [];
		this.movieName = "SWFUpload_" + SWFUpload.movieCount++;
		this.movieElement = null;


		// Setup global control tracking
		SWFUpload.instances[this.movieName] = this;

		// Load the settings.  Load the Flash movie.
		this.initSettings();
		this.loadFlash();
		this.displayDebugInfo();
	} catch (ex) {
		delete SWFUpload.instances[this.movieName];
		throw ex;
	}
};

/* *************** */
/* Static Members  */
/* *************** */
SWFUpload.instances = {};
SWFUpload.movieCount = 0;
SWFUpload.version = "2.2.0 2009-03-25";
SWFUpload.QUEUE_ERROR = {
	QUEUE_LIMIT_EXCEEDED	  		: -100,
	FILE_EXCEEDS_SIZE_LIMIT  		: -110,
	ZERO_BYTE_FILE			  		: -120,
	INVALID_FILETYPE		  		: -130
};
SWFUpload.UPLOAD_ERROR = {
	HTTP_ERROR				  		: -200,
	MISSING_UPLOAD_URL	      		: -210,
	IO_ERROR				  		: -220,
	SECURITY_ERROR			  		: -230,
	UPLOAD_LIMIT_EXCEEDED	  		: -240,
	UPLOAD_FAILED			  		: -250,
	SPECIFIED_FILE_ID_NOT_FOUND		: -260,
	FILE_VALIDATION_FAILED	  		: -270,
	FILE_CANCELLED			  		: -280,
	UPLOAD_STOPPED					: -290
};
SWFUpload.FILE_STATUS = {
	QUEUED		 : -1,
	IN_PROGRESS	 : -2,
	ERROR		 : -3,
	COMPLETE	 : -4,
	CANCELLED	 : -5
};
SWFUpload.BUTTON_ACTION = {
	SELECT_FILE  : -100,
	SELECT_FILES : -110,
	START_UPLOAD : -120
};
SWFUpload.CURSOR = {
	ARROW : -1,
	HAND : -2
};
SWFUpload.WINDOW_MODE = {
	WINDOW : "window",
	TRANSPARENT : "transparent",
	OPAQUE : "opaque"
};

// Private: takes a URL, determines if it is relative and converts to an absolute URL
// using the current site. Only processes the URL if it can, otherwise returns the URL untouched
SWFUpload.completeURL = function(url) {
	if (typeof(url) !== "string" || url.match(/^https?:\/\//i) || url.match(/^\//)) {
		return url;
	}
	
	var currentURL = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : "");
	
	var indexSlash = window.location.pathname.lastIndexOf("/");
	if (indexSlash <= 0) {
		path = "/";
	} else {
		path = window.location.pathname.substr(0, indexSlash) + "/";
	}
	
	return /*currentURL +*/ path + url;
	
};


/* ******************** */
/* Instance Members  */
/* ******************** */

// Private: initSettings ensures that all the
// settings are set, getting a default value if one was not assigned.
SWFUpload.prototype.initSettings = function () {
	this.ensureDefault = function (settingName, defaultValue) {
		this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
	};
	
	// Upload backend settings
	this.ensureDefault("upload_url", "");
	this.ensureDefault("preserve_relative_urls", false);
	this.ensureDefault("file_post_name", "Filedata");
	this.ensureDefault("post_params", {});
	this.ensureDefault("use_query_string", false);
	this.ensureDefault("requeue_on_error", false);
	this.ensureDefault("http_success", []);
	this.ensureDefault("assume_success_timeout", 0);
	
	// File Settings
	this.ensureDefault("file_types", "*.*");
	this.ensureDefault("file_types_description", "All Files");
	this.ensureDefault("file_size_limit", 0);	// Default zero means "unlimited"
	this.ensureDefault("file_upload_limit", 0);
	this.ensureDefault("file_queue_limit", 0);

	// Flash Settings
	this.ensureDefault("flash_url", "swfupload.swf");
	this.ensureDefault("prevent_swf_caching", true);
	
	// Button Settings
	this.ensureDefault("button_image_url", "");
	this.ensureDefault("button_width", 1);
	this.ensureDefault("button_height", 1);
	this.ensureDefault("button_text", "");
	this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;");
	this.ensureDefault("button_text_top_padding", 0);
	this.ensureDefault("button_text_left_padding", 0);
	this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES);
	this.ensureDefault("button_disabled", false);
	this.ensureDefault("button_placeholder_id", "");
	this.ensureDefault("button_placeholder", null);
	this.ensureDefault("button_cursor", SWFUpload.CURSOR.ARROW);
	this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.WINDOW);
	
	// Debug Settings
	this.ensureDefault("debug", false);
	this.settings.debug_enabled = this.settings.debug;	// Here to maintain v2 API
	
	// Event Handlers
	this.settings.return_upload_start_handler = this.returnUploadStart;
	this.ensureDefault("swfupload_loaded_handler", null);
	this.ensureDefault("file_dialog_start_handler", null);
	this.ensureDefault("file_queued_handler", null);
	this.ensureDefault("file_queue_error_handler", null);
	this.ensureDefault("file_dialog_complete_handler", null);
	
	this.ensureDefault("upload_start_handler", null);
	this.ensureDefault("upload_progress_handler", null);
	this.ensureDefault("upload_error_handler", null);
	this.ensureDefault("upload_success_handler", null);
	this.ensureDefault("upload_complete_handler", null);
	
	this.ensureDefault("debug_handler", this.debugMessage);

	this.ensureDefault("custom_settings", {});

	// Other settings
	this.customSettings = this.settings.custom_settings;
	
	// Update the flash url if needed
	if (!!this.settings.prevent_swf_caching) {
		this.settings.flash_url = this.settings.flash_url + (this.settings.flash_url.indexOf("?") < 0 ? "?" : "&") + "preventswfcaching=" + new Date().getTime();
	}
	
	if (!this.settings.preserve_relative_urls) {
		//this.settings.flash_url = SWFUpload.completeURL(this.settings.flash_url);	// Don't need to do this one since flash doesn't look at it
		this.settings.upload_url = SWFUpload.completeURL(this.settings.upload_url);
		this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url);
	}
	
	delete this.ensureDefault;
};

// Private: loadFlash replaces the button_placeholder element with the flash movie.
SWFUpload.prototype.loadFlash = function () {
	var targetElement, tempParent;

	// Make sure an element with the ID we are going to use doesn't already exist
	if (document.getElementById(this.movieName) !== null) {
		throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";
	}

	// Get the element where we will be placing the flash movie
	targetElement = document.getElementById(this.settings.button_placeholder_id) || this.settings.button_placeholder;

	if (targetElement == undefined) {
		throw "Could not find the placeholder element: " + this.settings.button_placeholder_id;
	}

	// Append the container and load the flash
	tempParent = document.createElement("div");
	tempParent.innerHTML = this.getFlashHTML();	// Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers)
	targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement);

	// Fix IE Flash/Form bug
	if (window[this.movieName] == undefined) {
		window[this.movieName] = this.getMovieElement();
	}
	
};

// Private: getFlashHTML generates the object tag needed to embed the flash in to the document
SWFUpload.prototype.getFlashHTML = function () {
	// Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay
	return ['<object id="', this.movieName, '" type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">',
				'<param name="wmode" value="', this.settings.button_window_mode, '" />',
				'<param name="movie" value="', this.settings.flash_url, '" />',
				'<param name="quality" value="high" />',
				'<param name="menu" value="false" />',
				'<param name="allowScriptAccess" value="always" />',
				'<param name="flashvars" value="' + this.getFlashVars() + '" />',
				'</object>'].join("");
};

// Private: getFlashVars builds the parameter string that will be passed
// to flash in the flashvars param.
SWFUpload.prototype.getFlashVars = function () {
	// Build a string from the post param object
	var paramString = this.buildParamString();
	var httpSuccessString = this.settings.http_success.join(",");
	
	// Build the parameter string
	return ["movieName=", encodeURIComponent(this.movieName),
			"&amp;uploadURL=", encodeURIComponent(this.settings.upload_url),
			"&amp;useQueryString=", encodeURIComponent(this.settings.use_query_string),
			"&amp;requeueOnError=", encodeURIComponent(this.settings.requeue_on_error),
			"&amp;httpSuccess=", encodeURIComponent(httpSuccessString),
			"&amp;assumeSuccessTimeout=", encodeURIComponent(this.settings.assume_success_timeout),
			"&amp;params=", encodeURIComponent(paramString),
			"&amp;filePostName=", encodeURIComponent(this.settings.file_post_name),
			"&amp;fileTypes=", encodeURIComponent(this.settings.file_types),
			"&amp;fileTypesDescription=", encodeURIComponent(this.settings.file_types_description),
			"&amp;fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit),
			"&amp;fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit),
			"&amp;fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit),
			"&amp;debugEnabled=", encodeURIComponent(this.settings.debug_enabled),
			"&amp;buttonImageURL=", encodeURIComponent(this.settings.button_image_url),
			"&amp;buttonWidth=", encodeURIComponent(this.settings.button_width),
			"&amp;buttonHeight=", encodeURIComponent(this.settings.button_height),
			"&amp;buttonText=", encodeURIComponent(this.settings.button_text),
			"&amp;buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding),
			"&amp;buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding),
			"&amp;buttonTextStyle=", encodeURIComponent(this.settings.button_text_style),
			"&amp;buttonAction=", encodeURIComponent(this.settings.button_action),
			"&amp;buttonDisabled=", encodeURIComponent(this.settings.button_disabled),
			"&amp;buttonCursor=", encodeURIComponent(this.settings.button_cursor)
		].join("");
};

// Public: getMovieElement retrieves the DOM reference to the Flash element added by SWFUpload
// The element is cached after the first lookup
SWFUpload.prototype.getMovieElement = function () {
	if (this.movieElement == undefined) {
		this.movieElement = document.getElementById(this.movieName);
	}

	if (this.movieElement === null) {
		throw "Could not find Flash element";
	}
	
	return this.movieElement;
};

// Private: buildParamString takes the name/value pairs in the post_params setting object
// and joins them up in to a string formatted "name=value&amp;name=value"
SWFUpload.prototype.buildParamString = function () {
	var postParams = this.settings.post_params; 
	var paramStringPairs = [];

	if (typeof(postParams) === "object") {
		for (var name in postParams) {
			if (postParams.hasOwnProperty(name)) {
				paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString()));
			}
		}
	}

	return paramStringPairs.join("&amp;");
};

// Public: Used to remove a SWFUpload instance from the page. This method strives to remove
// all references to the SWF, and other objects so memory is properly freed.
// Returns true if everything was destroyed. Returns a false if a failure occurs leaving SWFUpload in an inconsistant state.
// Credits: Major improvements provided by steffen
SWFUpload.prototype.destroy = function () {
	try {
		// Make sure Flash is done before we try to remove it
		this.cancelUpload(null, false);
		

		// Remove the SWFUpload DOM nodes
		var movieElement = null;
		movieElement = this.getMovieElement();
		
		if (movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
			// Loop through all the movie's properties and remove all function references (DOM/JS IE 6/7 memory leak workaround)
			for (var i in movieElement) {
				try {
					if (typeof(movieElement[i]) === "function") {
						movieElement[i] = null;
					}
				} catch (ex1) {}
			}

			// Remove the Movie Element from the page
			try {
				movieElement.parentNode.removeChild(movieElement);
			} catch (ex) {}
		}
		
		// Remove IE form fix reference
		window[this.movieName] = null;

		// Destroy other references
		SWFUpload.instances[this.movieName] = null;
		delete SWFUpload.instances[this.movieName];

		this.movieElement = null;
		this.settings = null;
		this.customSettings = null;
		this.eventQueue = null;
		this.movieName = null;
		
		
		return true;
	} catch (ex2) {
		return false;
	}
};


// Public: displayDebugInfo prints out settings and configuration
// information about this SWFUpload instance.
// This function (and any references to it) can be deleted when placing
// SWFUpload in production.
SWFUpload.prototype.displayDebugInfo = function () {
	this.debug(
		[
			"---SWFUpload Instance Info---\n",
			"Version: ", SWFUpload.version, "\n",
			"Movie Name: ", this.movieName, "\n",
			"Settings:\n",
			"\t", "upload_url:               ", this.settings.upload_url, "\n",
			"\t", "flash_url:                ", this.settings.flash_url, "\n",
			"\t", "use_query_string:         ", this.settings.use_query_string.toString(), "\n",
			"\t", "requeue_on_error:         ", this.settings.requeue_on_error.toString(), "\n",
			"\t", "http_success:             ", this.settings.http_success.join(", "), "\n",
			"\t", "assume_success_timeout:   ", this.settings.assume_success_timeout, "\n",
			"\t", "file_post_name:           ", this.settings.file_post_name, "\n",
			"\t", "post_params:              ", this.settings.post_params.toString(), "\n",
			"\t", "file_types:               ", this.settings.file_types, "\n",
			"\t", "file_types_description:   ", this.settings.file_types_description, "\n",
			"\t", "file_size_limit:          ", this.settings.file_size_limit, "\n",
			"\t", "file_upload_limit:        ", this.settings.file_upload_limit, "\n",
			"\t", "file_queue_limit:         ", this.settings.file_queue_limit, "\n",
			"\t", "debug:                    ", this.settings.debug.toString(), "\n",

			"\t", "prevent_swf_caching:      ", this.settings.prevent_swf_caching.toString(), "\n",

			"\t", "button_placeholder_id:    ", this.settings.button_placeholder_id.toString(), "\n",
			"\t", "button_placeholder:       ", (this.settings.button_placeholder ? "Set" : "Not Set"), "\n",
			"\t", "button_image_url:         ", this.settings.button_image_url.toString(), "\n",
			"\t", "button_width:             ", this.settings.button_width.toString(), "\n",
			"\t", "button_height:            ", this.settings.button_height.toString(), "\n",
			"\t", "button_text:              ", this.settings.button_text.toString(), "\n",
			"\t", "button_text_style:        ", this.settings.button_text_style.toString(), "\n",
			"\t", "button_text_top_padding:  ", this.settings.button_text_top_padding.toString(), "\n",
			"\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n",
			"\t", "button_action:            ", this.settings.button_action.toString(), "\n",
			"\t", "button_disabled:          ", this.settings.button_disabled.toString(), "\n",

			"\t", "custom_settings:          ", this.settings.custom_settings.toString(), "\n",
			"Event Handlers:\n",
			"\t", "swfupload_loaded_handler assigned:  ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n",
			"\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n",
			"\t", "file_queued_handler assigned:       ", (typeof this.settings.file_queued_handler === "function").toString(), "\n",
			"\t", "file_queue_error_handler assigned:  ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n",
			"\t", "upload_start_handler assigned:      ", (typeof this.settings.upload_start_handler === "function").toString(), "\n",
			"\t", "upload_progress_handler assigned:   ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n",
			"\t", "upload_error_handler assigned:      ", (typeof this.settings.upload_error_handler === "function").toString(), "\n",
			"\t", "upload_success_handler assigned:    ", (typeof this.settings.upload_success_handler === "function").toString(), "\n",
			"\t", "upload_complete_handler assigned:   ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n",
			"\t", "debug_handler assigned:             ", (typeof this.settings.debug_handler === "function").toString(), "\n"
		].join("")
	);
};

/* Note: addSetting and getSetting are no longer used by SWFUpload but are included
	the maintain v2 API compatibility
*/
// Public: (Deprecated) addSetting adds a setting value. If the value given is undefined or null then the default_value is used.
SWFUpload.prototype.addSetting = function (name, value, default_value) {
    if (value == undefined) {
        return (this.settings[name] = default_value);
    } else {
        return (this.settings[name] = value);
	}
};

// Public: (Deprecated) getSetting gets a setting. Returns an empty string if the setting was not found.
SWFUpload.prototype.getSetting = function (name) {
    if (this.settings[name] != undefined) {
        return this.settings[name];
	}

    return "";
};



// Private: callFlash handles function calls made to the Flash element.
// Calls are made with a setTimeout for some functions to work around
// bugs in the ExternalInterface library.
SWFUpload.prototype.callFlash = function (functionName, argumentArray) {
	argumentArray = argumentArray || [];
	
	var movieElement = this.getMovieElement();
	var returnValue, returnString;

	// Flash's method if calling ExternalInterface methods (code adapted from MooTools).
	try {
		returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>');
		returnValue = eval(returnString);
	} catch (ex) {
		throw "Call to " + functionName + " failed";
	}
	
	// Unescape file post param values
	if (returnValue != undefined && typeof returnValue.post === "object") {
		returnValue = this.unescapeFilePostParams(returnValue);
	}

	return returnValue;
};

/* *****************************
	-- Flash control methods --
	Your UI should use these
	to operate SWFUpload
   ***************************** */

// WARNING: this function does not work in Flash Player 10
// Public: selectFile causes a File Selection Dialog window to appear.  This
// dialog only allows 1 file to be selected.
SWFUpload.prototype.selectFile = function () {
	this.callFlash("SelectFile");
};

// WARNING: this function does not work in Flash Player 10
// Public: selectFiles causes a File Selection Dialog window to appear/ This
// dialog allows the user to select any number of files
// Flash Bug Warning: Flash limits the number of selectable files based on the combined length of the file names.
// If the selection name length is too long the dialog will fail in an unpredictable manner.  There is no work-around
// for this bug.
SWFUpload.prototype.selectFiles = function () {
	this.callFlash("SelectFiles");
};


// Public: startUpload starts uploading the first file in the queue unless
// the optional parameter 'fileID' specifies the ID 
SWFUpload.prototype.startUpload = function (fileID) {
	this.callFlash("StartUpload", [fileID]);
};

// Public: cancelUpload cancels any queued file.  The fileID parameter may be the file ID or index.
// If you do not specify a fileID the current uploading file or first file in the queue is cancelled.
// If you do not want the uploadError event to trigger you can specify false for the triggerErrorEvent parameter.
SWFUpload.prototype.cancelUpload = function (fileID, triggerErrorEvent) {
	if (triggerErrorEvent !== false) {
		triggerErrorEvent = true;
	}
	this.callFlash("CancelUpload", [fileID, triggerErrorEvent]);
};

// Public: stopUpload stops the current upload and requeues the file at the beginning of the queue.
// If nothing is currently uploading then nothing happens.
SWFUpload.prototype.stopUpload = function () {
	this.callFlash("StopUpload");
};

/* ************************
 * Settings methods
 *   These methods change the SWFUpload settings.
 *   SWFUpload settings should not be changed directly on the settings object
 *   since many of the settings need to be passed to Flash in order to take
 *   effect.
 * *********************** */

// Public: getStats gets the file statistics object.
SWFUpload.prototype.getStats = function () {
	return this.callFlash("GetStats");
};

// Public: setStats changes the SWFUpload statistics.  You shouldn't need to 
// change the statistics but you can.  Changing the statistics does not
// affect SWFUpload accept for the successful_uploads count which is used
// by the upload_limit setting to determine how many files the user may upload.
SWFUpload.prototype.setStats = function (statsObject) {
	this.callFlash("SetStats", [statsObject]);
};

// Public: getFile retrieves a File object by ID or Index.  If the file is
// not found then 'null' is returned.
SWFUpload.prototype.getFile = function (fileID) {
	if (typeof(fileID) === "number") {
		return this.callFlash("GetFileByIndex", [fileID]);
	} else {
		return this.callFlash("GetFile", [fileID]);
	}
};

// Public: addFileParam sets a name/value pair that will be posted with the
// file specified by the Files ID.  If the name already exists then the
// exiting value will be overwritten.
SWFUpload.prototype.addFileParam = function (fileID, name, value) {
	return this.callFlash("AddFileParam", [fileID, name, value]);
};

// Public: removeFileParam removes a previously set (by addFileParam) name/value
// pair from the specified file.
SWFUpload.prototype.removeFileParam = function (fileID, name) {
	this.callFlash("RemoveFileParam", [fileID, name]);
};

// Public: setUploadUrl changes the upload_url setting.
SWFUpload.prototype.setUploadURL = function (url) {
	this.settings.upload_url = url.toString();
	this.callFlash("SetUploadURL", [url]);
};

// Public: setPostParams changes the post_params setting
SWFUpload.prototype.setPostParams = function (paramsObject) {
	this.settings.post_params = paramsObject;
	this.callFlash("SetPostParams", [paramsObject]);
};

// Public: addPostParam adds post name/value pair.  Each name can have only one value.
SWFUpload.prototype.addPostParam = function (name, value) {
	this.settings.post_params[name] = value;
	this.callFlash("SetPostParams", [this.settings.post_params]);
};

// Public: removePostParam deletes post name/value pair.
SWFUpload.prototype.removePostParam = function (name) {
	delete this.settings.post_params[name];
	this.callFlash("SetPostParams", [this.settings.post_params]);
};

// Public: setFileTypes changes the file_types setting and the file_types_description setting
SWFUpload.prototype.setFileTypes = function (types, description) {
	this.settings.file_types = types;
	this.settings.file_types_description = description;
	this.callFlash("SetFileTypes", [types, description]);
};

// Public: setFileSizeLimit changes the file_size_limit setting
SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) {
	this.settings.file_size_limit = fileSizeLimit;
	this.callFlash("SetFileSizeLimit", [fileSizeLimit]);
};

// Public: setFileUploadLimit changes the file_upload_limit setting
SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) {
	this.settings.file_upload_limit = fileUploadLimit;
	this.callFlash("SetFileUploadLimit", [fileUploadLimit]);
};

// Public: setFileQueueLimit changes the file_queue_limit setting
SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) {
	this.settings.file_queue_limit = fileQueueLimit;
	this.callFlash("SetFileQueueLimit", [fileQueueLimit]);
};

// Public: setFilePostName changes the file_post_name setting
SWFUpload.prototype.setFilePostName = function (filePostName) {
	this.settings.file_post_name = filePostName;
	this.callFlash("SetFilePostName", [filePostName]);
};

// Public: setUseQueryString changes the use_query_string setting
SWFUpload.prototype.setUseQueryString = function (useQueryString) {
	this.settings.use_query_string = useQueryString;
	this.callFlash("SetUseQueryString", [useQueryString]);
};

// Public: setRequeueOnError changes the requeue_on_error setting
SWFUpload.prototype.setRequeueOnError = function (requeueOnError) {
	this.settings.requeue_on_error = requeueOnError;
	this.callFlash("SetRequeueOnError", [requeueOnError]);
};

// Public: setHTTPSuccess changes the http_success setting
SWFUpload.prototype.setHTTPSuccess = function (http_status_codes) {
	if (typeof http_status_codes === "string") {
		http_status_codes = http_status_codes.replace(" ", "").split(",");
	}
	
	this.settings.http_success = http_status_codes;
	this.callFlash("SetHTTPSuccess", [http_status_codes]);
};

// Public: setHTTPSuccess changes the http_success setting
SWFUpload.prototype.setAssumeSuccessTimeout = function (timeout_seconds) {
	this.settings.assume_success_timeout = timeout_seconds;
	this.callFlash("SetAssumeSuccessTimeout", [timeout_seconds]);
};

// Public: setDebugEnabled changes the debug_enabled setting
SWFUpload.prototype.setDebugEnabled = function (debugEnabled) {
	this.settings.debug_enabled = debugEnabled;
	this.callFlash("SetDebugEnabled", [debugEnabled]);
};

// Public: setButtonImageURL loads a button image sprite
SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) {
	if (buttonImageURL == undefined) {
		buttonImageURL = "";
	}
	
	this.settings.button_image_url = buttonImageURL;
	this.callFlash("SetButtonImageURL", [buttonImageURL]);
};

// Public: setButtonDimensions resizes the Flash Movie and button
SWFUpload.prototype.setButtonDimensions = function (width, height) {
	this.settings.button_width = width;
	this.settings.button_height = height;
	
	var movie = this.getMovieElement();
	if (movie != undefined) {
		movie.style.width = width + "px";
		movie.style.height = height + "px";
	}
	
	this.callFlash("SetButtonDimensions", [width, height]);
};
// Public: setButtonText Changes the text overlaid on the button
SWFUpload.prototype.setButtonText = function (html) {
	this.settings.button_text = html;
	this.callFlash("SetButtonText", [html]);
};
// Public: setButtonTextPadding changes the top and left padding of the text overlay
SWFUpload.prototype.setButtonTextPadding = function (left, top) {
	this.settings.button_text_top_padding = top;
	this.settings.button_text_left_padding = left;
	this.callFlash("SetButtonTextPadding", [left, top]);
};

// Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button
SWFUpload.prototype.setButtonTextStyle = function (css) {
	this.settings.button_text_style = css;
	this.callFlash("SetButtonTextStyle", [css]);
};
// Public: setButtonDisabled disables/enables the button
SWFUpload.prototype.setButtonDisabled = function (isDisabled) {
	this.settings.button_disabled = isDisabled;
	this.callFlash("SetButtonDisabled", [isDisabled]);
};
// Public: setButtonAction sets the action that occurs when the button is clicked
SWFUpload.prototype.setButtonAction = function (buttonAction) {
	this.settings.button_action = buttonAction;
	this.callFlash("SetButtonAction", [buttonAction]);
};

// Public: setButtonCursor changes the mouse cursor displayed when hovering over the button
SWFUpload.prototype.setButtonCursor = function (cursor) {
	this.settings.button_cursor = cursor;
	this.callFlash("SetButtonCursor", [cursor]);
};

/* *******************************
	Flash Event Interfaces
	These functions are used by Flash to trigger the various
	events.
	
	All these functions a Private.
	
	Because the ExternalInterface library is buggy the event calls
	are added to a queue and the queue then executed by a setTimeout.
	This ensures that events are executed in a determinate order and that
	the ExternalInterface bugs are avoided.
******************************* */

SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) {
	// Warning: Don't call this.debug inside here or you'll create an infinite loop
	
	if (argumentArray == undefined) {
		argumentArray = [];
	} else if (!(argumentArray instanceof Array)) {
		argumentArray = [argumentArray];
	}
	
	var self = this;
	if (typeof this.settings[handlerName] === "function") {
		// Queue the event
		this.eventQueue.push(function () {
			this.settings[handlerName].apply(this, argumentArray);
		});
		
		// Execute the next queued event
		setTimeout(function () {
			self.executeNextEvent();
		}, 0);
		
	} else if (this.settings[handlerName] !== null) {
		throw "Event handler " + handlerName + " is unknown or is not a function";
	}
};

// Private: Causes the next event in the queue to be executed.  Since events are queued using a setTimeout
// we must queue them in order to garentee that they are executed in order.
SWFUpload.prototype.executeNextEvent = function () {
	// Warning: Don't call this.debug inside here or you'll create an infinite loop

	var  f = this.eventQueue ? this.eventQueue.shift() : null;
	if (typeof(f) === "function") {
		f.apply(this);
	}
};

// Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterface cannot have
// properties that contain characters that are not valid for JavaScript identifiers. To work around this
// the Flash Component escapes the parameter names and we must unescape again before passing them along.
SWFUpload.prototype.unescapeFilePostParams = function (file) {
	var reg = /[$]([0-9a-f]{4})/i;
	var unescapedPost = {};
	var uk;

	if (file != undefined) {
		for (var k in file.post) {
			if (file.post.hasOwnProperty(k)) {
				uk = k;
				var match;
				while ((match = reg.exec(uk)) !== null) {
					uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16)));
				}
				unescapedPost[uk] = file.post[k];
			}
		}

		file.post = unescapedPost;
	}

	return file;
};

// Private: Called by Flash to see if JS can call in to Flash (test if External Interface is working)
SWFUpload.prototype.testExternalInterface = function () {
	try {
		return this.callFlash("TestExternalInterface");
	} catch (ex) {
		return false;
	}
};

// Private: This event is called by Flash when it has finished loading. Don't modify this.
// Use the swfupload_loaded_handler event setting to execute custom code when SWFUpload has loaded.
SWFUpload.prototype.flashReady = function () {
	// Check that the movie element is loaded correctly with its ExternalInterface methods defined
	var movieElement = this.getMovieElement();

	if (!movieElement) {
		this.debug("Flash called back ready but the flash movie can't be found.");
		return;
	}

	this.cleanUp(movieElement);
	
	this.queueEvent("swfupload_loaded_handler");
};

// Private: removes Flash added fuctions to the DOM node to prevent memory leaks in IE.
// This function is called by Flash each time the ExternalInterface functions are created.
SWFUpload.prototype.cleanUp = function (movieElement) {
	// Pro-actively unhook all the Flash functions
	try {
		if (this.movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
			this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");
			for (var key in movieElement) {
				try {
					if (typeof(movieElement[key]) === "function") {
						movieElement[key] = null;
					}
				} catch (ex) {
				}
			}
		}
	} catch (ex1) {
	
	}

	// Fix Flashes own cleanup code so if the SWFMovie was removed from the page
	// it doesn't display errors.
	window["__flash__removeCallback"] = function (instance, name) {
		try {
			if (instance) {
				instance[name] = null;
			}
		} catch (flashEx) {
		
		}
	};

};


/* This is a chance to do something before the browse window opens */
SWFUpload.prototype.fileDialogStart = function () {
	this.queueEvent("file_dialog_start_handler");
};


/* Called when a file is successfully added to the queue. */
SWFUpload.prototype.fileQueued = function (file) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("file_queued_handler", file);
};


/* Handle errors that occur when an attempt to queue a file fails. */
SWFUpload.prototype.fileQueueError = function (file, errorCode, message) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("file_queue_error_handler", [file, errorCode, message]);
};

/* Called after the file dialog has closed and the selected files have been queued.
	You could call startUpload here if you want the queued files to begin uploading immediately. */
SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued, numFilesInQueue) {
	this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued, numFilesInQueue]);
};

SWFUpload.prototype.uploadStart = function (file) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("return_upload_start_handler", file);
};

SWFUpload.prototype.returnUploadStart = function (file) {
	var returnValue;
	if (typeof this.settings.upload_start_handler === "function") {
		file = this.unescapeFilePostParams(file);
		returnValue = this.settings.upload_start_handler.call(this, file);
	} else if (this.settings.upload_start_handler != undefined) {
		throw "upload_start_handler must be a function";
	}

	// Convert undefined to true so if nothing is returned from the upload_start_handler it is
	// interpretted as 'true'.
	if (returnValue === undefined) {
		returnValue = true;
	}
	
	returnValue = !!returnValue;
	
	this.callFlash("ReturnUploadStart", [returnValue]);
};



SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]);
};

SWFUpload.prototype.uploadError = function (file, errorCode, message) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("upload_error_handler", [file, errorCode, message]);
};

SWFUpload.prototype.uploadSuccess = function (file, serverData, responseReceived) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("upload_success_handler", [file, serverData, responseReceived]);
};

SWFUpload.prototype.uploadComplete = function (file) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("upload_complete_handler", file);
};

/* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the
   internal debug console.  You can override this event and have messages written where you want. */
SWFUpload.prototype.debug = function (message) {
	this.queueEvent("debug_handler", message);
};


/* **********************************
	Debug Console
	The debug console is a self contained, in page location
	for debug message to be sent.  The Debug Console adds
	itself to the body if necessary.

	The console is automatically scrolled as messages appear.
	
	If you are using your own debug handler or when you deploy to production and
	have debug disabled you can remove these functions to reduce the file size
	and complexity.
********************************** */
   
// Private: debugMessage is the default debug_handler.  If you want to print debug messages
// call the debug() function.  When overriding the function your own function should
// check to see if the debug setting is true before outputting debug information.
SWFUpload.prototype.debugMessage = function (message) {
	if (this.settings.debug) {
		var exceptionMessage, exceptionValues = [];

		// Check for an exception object and print it nicely
		if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") {
			for (var key in message) {
				if (message.hasOwnProperty(key)) {
					exceptionValues.push(key + ": " + message[key]);
				}
			}
			exceptionMessage = exceptionValues.join("\n") || "";
			exceptionValues = exceptionMessage.split("\n");
			exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: ");
			SWFUpload.Console.writeLine(exceptionMessage);
		} else {
			SWFUpload.Console.writeLine(message);
		}
	}
};

SWFUpload.Console = {};
SWFUpload.Console.writeLine = function (message) {
	var console, documentForm;

	try {
		console = document.getElementById("SWFUpload_Console");

		if (!console) {
			documentForm = document.createElement("form");
			document.getElementsByTagName("body")[0].appendChild(documentForm);

			console = document.createElement("textarea");
			console.id = "SWFUpload_Console";
			console.style.fontFamily = "monospace";
			console.setAttribute("wrap", "off");
			console.wrap = "off";
			console.style.overflow = "auto";
			console.style.width = "700px";
			console.style.height = "350px";
			console.style.margin = "5px";
			documentForm.appendChild(console);
		}

		console.value += message + "\n";

		console.scrollTop = console.scrollHeight - console.clientHeight;
	} catch (ex) {
		alert("Exception: " + ex.name + " Message: " + ex.message);
	}
};

/*
	Queue Plug-in
	
	Features:
		*Adds a cancelQueue() method for cancelling the entire queue.
		*All queued files are uploaded when startUpload() is called.
		*If false is returned from uploadComplete then the queue upload is stopped.
		 If false is not returned (strict comparison) then the queue upload is continued.
		*Adds a QueueComplete event that is fired when all the queued files have finished uploading.
		 Set the event handler with the queue_complete_handler setting.
		
	*/

var SWFUpload;
if (typeof(SWFUpload) === "function") {
	SWFUpload.queue = {};
	
	SWFUpload.prototype.initSettings = (function (oldInitSettings) {
		return function () {
			if (typeof(oldInitSettings) === "function") {
				oldInitSettings.call(this);
			}
			
			this.queueSettings = {};
			
			this.queueSettings.queue_cancelled_flag = false;
			this.queueSettings.queue_upload_count = 0;
			
			this.queueSettings.user_upload_complete_handler = this.settings.upload_complete_handler;
			this.queueSettings.user_upload_start_handler = this.settings.upload_start_handler;
			this.settings.upload_complete_handler = SWFUpload.queue.uploadCompleteHandler;
			this.settings.upload_start_handler = SWFUpload.queue.uploadStartHandler;
			
			this.settings.queue_complete_handler = this.settings.queue_complete_handler || null;
		};
	})(SWFUpload.prototype.initSettings);

	SWFUpload.prototype.startUpload = function (fileID) {
		this.queueSettings.queue_cancelled_flag = false;
		this.callFlash("StartUpload", [fileID]);
	};

	SWFUpload.prototype.cancelQueue = function () {
		this.queueSettings.queue_cancelled_flag = true;
		this.stopUpload();
		
		var stats = this.getStats();
		while (stats.files_queued > 0) {
			this.cancelUpload();
			stats = this.getStats();
		}
	};
	
	SWFUpload.queue.uploadStartHandler = function (file) {
		var returnValue;
		if (typeof(this.queueSettings.user_upload_start_handler) === "function") {
			returnValue = this.queueSettings.user_upload_start_handler.call(this, file);
		}
		
		// To prevent upload a real "FALSE" value must be returned, otherwise default to a real "TRUE" value.
		returnValue = (returnValue === false) ? false : true;
		
		this.queueSettings.queue_cancelled_flag = !returnValue;

		return returnValue;
	};
	
	SWFUpload.queue.uploadCompleteHandler = function (file) {
		var user_upload_complete_handler = this.queueSettings.user_upload_complete_handler;
		var continueUpload;
		
		if (file.filestatus === SWFUpload.FILE_STATUS.COMPLETE) {
			this.queueSettings.queue_upload_count++;
		}

		if (typeof(user_upload_complete_handler) === "function") {
			continueUpload = (user_upload_complete_handler.call(this, file) === false) ? false : true;
		} else if (file.filestatus === SWFUpload.FILE_STATUS.QUEUED) {
			// If the file was stopped and re-queued don't restart the upload
			continueUpload = false;
		} else {
			continueUpload = true;
		}
		
		if (continueUpload) {
			var stats = this.getStats();
			if (stats.files_queued > 0 && this.queueSettings.queue_cancelled_flag === false) {
				this.startUpload();
			} else if (this.queueSettings.queue_cancelled_flag === false) {
				this.queueEvent("queue_complete_handler", [this.queueSettings.queue_upload_count]);
				this.queueSettings.queue_upload_count = 0;
			} else {
				this.queueSettings.queue_cancelled_flag = false;
				this.queueSettings.queue_upload_count = 0;
			}
		}
	};
}
/*
	A simple class for displaying file information and progress
	Note: This is a demonstration only and not part of SWFUpload.
	Note: Some have had problems adapting this class in IE7. It may not be suitable for your application.
*/

// Constructor
// file is a SWFUpload file object
// targetID is the HTML element id attribute that the FileProgress HTML structure will be added to.
// Instantiating a new FileProgress object with an existing file will reuse/update the existing DOM elements
function FileProgress(file, targetID) {
	this.fileProgressID = file.id;

	this.opacity = 100;
	this.height = 0;
	

	this.fileProgressWrapper = document.getElementById(this.fileProgressID);
	if (!this.fileProgressWrapper) {
		this.fileProgressWrapper = document.createElement("div");
		this.fileProgressWrapper.className = "progressWrapper";
		this.fileProgressWrapper.id = this.fileProgressID;

		this.fileProgressElement = document.createElement("div");
		this.fileProgressElement.className = "progressContainer";

		var progressCancel = document.createElement("a");
		progressCancel.className = "progressCancel";
		progressCancel.href = "#";
		progressCancel.style.visibility = "hidden";
		progressCancel.appendChild(document.createTextNode(" "));

		var progressText = document.createElement("div");
		progressText.className = "progressName";
		progressText.appendChild(document.createTextNode(file.name));

		var progressBar = document.createElement("div");
		progressBar.className = "progressBarInProgress";

		var progressStatus = document.createElement("div");
		progressStatus.className = "progressBarStatus";
		progressStatus.innerHTML = "&nbsp;";

		this.fileProgressElement.appendChild(progressCancel);
		this.fileProgressElement.appendChild(progressText);
		this.fileProgressElement.appendChild(progressStatus);
		this.fileProgressElement.appendChild(progressBar);

		this.fileProgressWrapper.appendChild(this.fileProgressElement);

		document.getElementById(targetID).appendChild(this.fileProgressWrapper);
	} else {
		this.fileProgressElement = this.fileProgressWrapper.firstChild;
		this.reset();
	}

	this.height = this.fileProgressWrapper.offsetHeight;
	this.setTimer(null);


}

FileProgress.prototype.setTimer = function (timer) {
	this.fileProgressElement["FP_TIMER"] = timer;
};
FileProgress.prototype.getTimer = function (timer) {
	return this.fileProgressElement["FP_TIMER"] || null;
};

FileProgress.prototype.reset = function () {
	this.fileProgressElement.className = "progressContainer";

	this.fileProgressElement.childNodes[2].innerHTML = "&nbsp;";
	this.fileProgressElement.childNodes[2].className = "progressBarStatus";
	
	this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
	this.fileProgressElement.childNodes[3].style.width = "0%";
	
	this.appear();	
};

FileProgress.prototype.setProgress = function (percentage) {
	this.fileProgressElement.className = "progressContainer";
	this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
	this.fileProgressElement.childNodes[3].style.width = percentage + "%";

	this.appear();	
};
FileProgress.prototype.setComplete = function () {
	this.fileProgressElement.className = "progressContainer";
	this.fileProgressElement.childNodes[3].className = "progressBarComplete";
	this.fileProgressElement.childNodes[3].style.width = "";

	var oSelf = this;
	this.setTimer(setTimeout(function () {
		oSelf.disappear();
	}, 10000));
};
FileProgress.prototype.setError = function () {
	this.fileProgressElement.className = "progressContainer";
	this.fileProgressElement.childNodes[3].className = "progressBarError";
	this.fileProgressElement.childNodes[3].style.width = "";

	var oSelf = this;
	this.setTimer(setTimeout(function () {
		oSelf.disappear();
	}, 5000));
};
FileProgress.prototype.setCancelled = function () {
	this.fileProgressElement.className = "progressContainer";
	this.fileProgressElement.childNodes[3].className = "progressBarError";
	this.fileProgressElement.childNodes[3].style.width = "";

	var oSelf = this;
	this.setTimer(setTimeout(function () {
		oSelf.disappear();
	}, 2000));
};
FileProgress.prototype.setStatus = function (status) {
	this.fileProgressElement.childNodes[2].innerHTML = status;
};

// Show/Hide the cancel button
FileProgress.prototype.toggleCancel = function (show, swfUploadInstance) {
	this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
	if (swfUploadInstance) {
		var fileID = this.fileProgressID;
		this.fileProgressElement.childNodes[0].onclick = function () {
			swfUploadInstance.cancelUpload(fileID);
			return false;
		};
	}
};

FileProgress.prototype.appear = function () {
	if (this.getTimer() !== null) {
		clearTimeout(this.getTimer());
		this.setTimer(null);
	}
	
	if (this.fileProgressWrapper.filters) {
		try {
			this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 100;
		} catch (e) {
			// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
			this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=100)";
		}
	} else {
		this.fileProgressWrapper.style.opacity = 1;
	}
		
	this.fileProgressWrapper.style.height = "";
	
	this.height = this.fileProgressWrapper.offsetHeight;
	this.opacity = 100;
	this.fileProgressWrapper.style.display = "";
	
};

// Fades out and clips away the FileProgress box.
FileProgress.prototype.disappear = function () {
/*
	var reduceOpacityBy = 15;
	var reduceHeightBy = 4;
	var rate = 30;	// 15 fps

	if (this.opacity > 0) {
		this.opacity -= reduceOpacityBy;
		if (this.opacity < 0) {
			this.opacity = 0;
		}

		if (this.fileProgressWrapper.filters) {
			try {
				this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = this.opacity;
			} catch (e) {
				// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
				this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + this.opacity + ")";
			}
		} else {
			this.fileProgressWrapper.style.opacity = this.opacity / 100;
		}
	}

	if (this.height > 0) {
		this.height -= reduceHeightBy;
		if (this.height < 0) {
			this.height = 0;
		}

		this.fileProgressWrapper.style.height = this.height + "px";
	}

	if (this.height > 0 || this.opacity > 0) {
		var oSelf = this;
		this.setTimer(setTimeout(function () {
			oSelf.disappear();
		}, rate));
	} else {
		this.fileProgressWrapper.style.display = "none";
		this.setTimer(null);
	}
	*/
};
/* This is an example of how to cancel all the files queued up.  It's made somewhat generic.  Just pass your SWFUpload
object in to this method and it loops through cancelling the uploads. */
/* **********************
   Event Handlers
   These are my custom event handlers to make my
   web application behave the way I went when SWFUpload
   completes different tasks.  These aren't part of the SWFUpload
   package.  They are part of my application.  Without these none
   of the actions SWFUpload makes will show up in my application.
   ********************** */
function fileDialogStart() {
	/* I don't need to do anything here */
}
function fileQueued(file) {
	try {
		// You might include code here that prevents the form from being submitted while the upload is in
		// progress.  Then you'll want to put code in the Queue Complete handler to "unblock" the form
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus("<div class='progressBarStatusHolder'><div style='width: 0%;'/></div></div>");
		progress.toggleCancel(true, this);
	} catch (ex) {
		this.debug(ex);
	}
}

function fileQueueError(file, errorCode, message) {
	try {
		if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
			alert("You have attempted to queue too many files.\n" + (message === 0 ? "You have reached the upload limit." : "You may select " + (message > 1 ? "up to " + message + " files." : "one file.")));
			return;
		}

		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
			progress.setStatus("File is too big.");
			this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
			progress.setStatus("Cannot upload Zero Byte files.");
			this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
			progress.setStatus("Invalid File Type.");
			this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
			alert("You have selected too many files.  " +  (message > 1 ? "You may only add " +  message + " more files" : "You cannot add any more files."));
			break;
		default:
			if (file !== null) {
				progress.setStatus("Unhandled Error");
			}
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}

function fileDialogComplete(numFilesSelected, numFilesQueued) {
	try {
		if (this.getStats().files_queued > 0) {
		}
		
		/* I want auto start and I can do that here */
		this.startUpload();
	} catch (ex)  {
        this.debug(ex);
	}
}

function uploadStart(file) {
	try {
	//	document.getElementById('upload_done').style.display = "block";
		/* I don't want to do any file validation or anything,  I'll just update the UI and return true to indicate that the upload should start */
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setStatus("<div style='width: 0%;'></div>");
		progress.toggleCancel(true, this);
	}
	catch (ex) {
	}
	
	return true;
}

function uploadProgress(file, bytesLoaded, bytesTotal) {

	try {
		var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);

		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setProgress(percent);
		progress.setStatus("<div style='width: "+percent+"%;'></div>");
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadSuccess(file, serverData) {
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setComplete();
		addImage(serverData);
		$(".progressWrapper:first").remove();
		progress.setComplete();
		progress.toggleCancel(false);
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadComplete(file) {
	try {
		/*  I want the next upload to continue automatically so I'll call startUpload here */
		if (this.getStats().files_queued === 0) {

		} else {	
			this.startUpload();
		}
	} catch (ex) {
		this.debug(ex);
	}

}

function uploadError(file, errorCode, message) {
	try {
		var progress = new FileProgress(file, this.customSettings.progressTarget);
		progress.setError();
		progress.toggleCancel(false);

		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
			progress.setStatus("Upload Error: " + message);
			this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
			progress.setStatus("Configuration Error");
			this.debug("Error Code: No backend file, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
			progress.setStatus("Upload Failed.");
			this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.IO_ERROR:
			progress.setStatus("Server (IO) Error");
			this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
			progress.setStatus("Security Error");
			this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			progress.setStatus("Upload limit exceeded.");
			this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
			progress.setStatus("File not found.");
			this.debug("Error Code: The file was not found, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
			progress.setStatus("Failed Validation.  Upload skipped.");
			this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
			if (this.getStats().files_queued === 0) {
			}
			progress.setStatus("Cancelled");
			progress.setCancelled();
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			progress.setStatus("Stopped");
			break;
		default:
			progress.setStatus("Unhandled Error: " + error_code);
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		}
	} catch (ex) {
        this.debug(ex);
    }
}

//used for adding thumbnails to supplier testimages upload
function addImage(url) {
	var id = url.split("/").pop();
	if(id > 0){
		var newImg = document.createElement("img");
		newImg.src = "/suppliers/showthumbnail/id/"+id;
		document.getElementById("thumbnails").appendChild(newImg);
		$(newImg).wrap('<div style="display:none; float:left;" id="supplier_testimage_'+id+'">');
		$(newImg).wrap("<div>");
		$("#supplier_testimage_"+id).append('<a style="margin-left: 48px;" class="supplier_removetestimage thumbnail_icons thumb_trash" href="' + url + '" /></a>');
		$(newImg).bind('load', function(){
			$("#supplier_testimage_"+id).fadeIn(1500);
			uploadcount = $(".supplier_removetestimage:visible").size();
			if(uploadcount == 5){
				$("#upload_done input").css("display", "block");
				$("#SWFUpload_0").css("display", "none");
			}else{
				$("#upload_done input").css("display", "none");
				$("#SWFUpload_0").css("display", "block");
			}
		});
	}
}
/**

MultiSelect v1.0
(c) Arc90, Inc.

http://www.arc90.com
http://lab.arc90.com

Licensed under : Creative Commons Attribution 2.5 http://creativecommons.org/licenses/by/2.5/

USAGE:
set JS vars in script with your choices:
a$.NO_SELECTION	= 'No selection';
a$.SELECTED		= 'Options selected';
a$.SelectAllMin	= 6;
a$.WhenToUse	= 'class';

for SELECT apply class="arc90_multiselect" if a$.WhenToUse == 'class' otherwise if if a$.WhenToUse == 'multiple' any select with multiple set will become a multiselect

*/

var a$ = {}; // arc90 namespace functions
a$.c = 0;
a$.openSelect = null;

a$.NO_SELECTION	= 'No selection';
a$.SELECTED		= 'Options selected';
a$.SELECT_ALL	= 'Select All';
a$.SelectAllMin	= 6;
a$.WhenToUse	= 'class'; // class: based on class arc90_multiselect existing | multiple: based on multiple attributte exists | all: both single and multiple
a$.msSeparator	= '|';

a$.appName = navigator.appVersion.toLowerCase();
a$.isIE = document.all && a$.appName.indexOf('msie') >= 0;
a$.isSafari = a$.appName.indexOf('safari') >= 0;
a$.msBodyTimer = null;

a$.multiSelectCreate = function(o) {
// can be called directly with the id or object passed in as the first argument
//  or if a$.WhenToUse is set to class or multiple
	var S = null;

	if (o != null)
		S = [a$.isString(o)? a$.e(o): o];
	else
		S = document.getElementsByTagName('select');

	for (var i = 0, l = 1; i < l; i++) { //S.length
		var s = S[i];
		if (s != null && ((a$.WhenToUse == 'class' &&  s.className.indexOf('arc90_multiselect') >= 0) || (a$.WhenToUse == 'multiple' && s.multiple) || (a$.WhenToUse == 'all'))) {
			var title = s.title, id = s.id, name = s.name;
			var div = a$.newNode('div', 'a9multiselect-'+ id, 'a9multiselect');
			var span = a$.newNode('div', 'a9multiselect-'+ id +'-title', 'title');
			span.setAttribute('title', title);
			var expcol = a$.newNode('div', 'a9multiselect-click-'+ id, 'expcol-click', '', span, div);
			var ul = a$.newNode('ul');
			if (a$.isIE)
				ul.style.width = '20em';
			var expbody = a$.newNode('div', 'a9multiselect-body-'+ id, 'expcol-body', '', ul);
			expbody.style.display = 'none';
			
			// Timer Events to auto-close the drop-down when not being used
			a$.newEvent(div, 'mouseout', function(event) { a$.msBodyTimer = setTimeout('a$.closeSelect("'+ id +'")', 1500); });
			a$.newEvent(div, 'mouseover', function(event) { clearTimeout(a$.msBodyTimer); a$.msBodyTimer = null; });
			a$.newEvent(expbody, 'mouseout', function(event) { a$.msBodyTimer = setTimeout('a$.closeSelect("'+ id +'")', 1500); });
			a$.newEvent(expbody, 'mouseover', function(event) { clearTimeout(a$.msBodyTimer); a$.msBodyTimer = null; });
			a$.newEvent(ul, 'mouseout', function(event) { clearTimeout(a$.msBodyTimer); a$.msBodyTimer = null; });
			a$.newEvent(ul, 'mouseover', function(event) { clearTimeout(a$.msBodyTimer); a$.msBodyTimer = null; });

			if (a$.isIE)
				var hidden = a$.newNode('<input type="hidden" name="'+ name +'" title="'+ title +'" />', name, '', '', null, div);
			else {
				var hidden = a$.newNode('input', name, '', '', null, div);
				hidden.setAttribute('type', 'hidden');
				hidden.setAttribute('name', name);
				hidden.setAttribute('title', title);
			}

			// insert select all option
			var m = s.options.length;
			if (s.multiple && m >= a$.SelectAllMin) {
				var alli = a$.newNode('li', 'a9selectall-'+ id, 'a9selectall', '', null, ul);
				if (a$.isIE) {
					var allbx = a$.newNode('<input type="checkbox" name="a$-'+ a$.c +'" id="a$-'+ a$.c +'" alt="'+ id +'" />', 'a$-'+ (a$.c++), '', '', null, alli);
					var allbl = a$.newNode('<label for="'+ allbx.id +'" />', '', '', a$.SELECT_ALL, null, alli);
				} else {
					var allbx = a$.newNode('input', 'a$-'+ a$.c++, '', '', null, alli);
					allbx.setAttribute('type', 'checkbox');
					allbx.setAttribute('alt', id);	
					var allbl = a$.newNode('label', '', '', a$.SELECT_ALL, null, alli);
					allbl.setAttribute('for', allbx.id);
				}

				// call to function to get every checkbox under 'a9multiselect-'+ id a$.T('input', a$.e('a9multiselect-'+ id))
				eval("a$.newEvent(allbx, 'click', function () { a$.selectAll(a$.e('"+ allbx.id +"')); a$.chk(a$.e('"+ allbx.id +"')); });");
			}
			var sel = 0;
			for (var j = 0; j < m; j++) {
				var value = s.options[j].value, text = s.options[j].text;
				var li = a$.newNode('li', 'a9-li-'+ a$.c, '', '', null, ul);
				
				var d = a$.newNode('div', '', '', '', null, li);
				var chkType = s.multiple? 'checkbox': 'radio';
				if (a$.isIE) {
					var checked = '', onclick = '';
					if (s.options[j].selected == true) {
						checked = ' checked="checked"';
						 // needed to allow checked entries to be imeadiately activated, but won't work when actually clicked
						onclick = " onclick=\"a$.multiSelect(this, '"+ value +"', 'a9multiselect-"+ id +"');\"";
						sel++;
					}
					var chkbx = a$.newNode('<input title="'+ s.options[j].text +'" name="a9multiselect-options-'+ id +'" alt="'+ id +'" type="'+ chkType +'"'+ checked + onclick +' value="'+ value +'" />', 'a$-'+ a$.c++, '_a9checkbox', '', null, li);
				} else {
					var chkbx = a$.newNode('input', 'a$-'+ a$.c++, '_a9checkbox', '', null, li);
					chkbx.setAttribute('type', chkType);
					chkbx.setAttribute('value', value);
					chkbx.setAttribute('alt', id);
					chkbx.setAttribute('title', s.options[j].text);
					chkbx.setAttribute('name', 'a9multiselect-options-'+ id);
					if (s.options[j].selected == true) {
						chkbx.checked = true;
						 // needed to allow checked entries to be imeadiately activated, but won't work when actually clicked
						chkbx.onclick = "a$.multiSelect(this, '"+ value +"', 'a9multiselect-"+ id +"');";
						sel++;
					}
				}

				a$.newEvent(chkbx, 'click', function(event) {
					a$.cancelbubble(event); // cancel so li event doesn't get activated
					if (a$.isIE) // IE has trouble with 'this' being used here
						var t = a$.e(document.activeElement.id);
					else
						var t = this;
					a$.multiSelect(t, t.value, 'a9multiselect-'+ t.alt);
					a$.chk(t);
					// uncheck the select all
					allbx = a$.t('input', a$.e('a9selectall-'+ t.alt));
					if (allbx) a$.chk(allbx, (allbx.checked = false));
				});

				a$.newEvent(li, 'click', function() {
					var t = a$.e('a$-'+ this.id.slice('a9-li-'.length));
					t.checked = !t.checked;
					a$.multiSelect(t, t.title, 'a9multiselect-'+ t.alt);
					a$.chk(t);
				});

				if (a$.isIE)
					var label = a$.newNode('<label onclick="a$.cancelbubble(event);" for="'+ chkbx.id +'" />', '', '', text, null, li);
				else {
					var label = a$.newNode('label', '', '', text, null, li);
					label.setAttribute('for', chkbx.id);
					a$.newEvent(label, 'click', function(event) { a$.cancelbubble(event); }); // cancel so li event doesn't get activated
				}

				// Hide Radio Buttons for Firefox
				if (chkType == 'radio' && !a$.isIE) {
					chkbx.style.visibility = 'hidden';
					label.style.marginLeft = '-18px';
				}
			}
			if (sel == m && allbx != null)
				allbx.setAttribute('checked', true);
			else if (sel == 0)
				span.innerHTML = a$.NO_SELECTION;

			var bs = a$.node_before(s);
			bs.appendChild(div);
			bs.appendChild(expbody);
			// check the className of s to look for fieldwidth- and valuewidth-
			// if a value is specified without format it's default is pixels
			// options are value: dynamic, 30, 30px, 30em, etc...
			// dynamic will only have a min-width value set
			// if valuewidth is missing, then it's min-width is set to fieldswidths (either default or specified using a$.getStyle)
			
			var fieldwidth = s.className.toLowerCase().indexOf('fieldwidth-');
			var valuewidth = s.className.toLowerCase().indexOf('valuewidth-');
			if (fieldwidth >= 0) {
				var q = s.className.slice(fieldwidth);
				fieldwidth = (q.slice(0, q.indexOf(' ') < 0? q.length: q.indexOf(' '))).slice('fieldwidth-'.length);
				fieldwidth = parseFloat(fieldwidth) == fieldwidth? fieldwidth+'px': fieldwidth;
			} else fieldwidth = '';
			if (valuewidth >= 0) {
				var q = s.className.slice(valuewidth);
				valuewidth = (q.slice(0, q.indexOf(' ') < 0? q.length: q.indexOf(' '))).slice('valuewidth-'.length);
				valuewidth = parseFloat(valuewidth) == valuewidth? valuewidth+'px': valuewidth;
			} else valuewidth = '';
			
			if (fieldwidth != 'dynamic') {
				expcol.style.width = fieldwidth;
				div.style.width = fieldwidth;
			}
			if (valuewidth != 'dynamic')
				expbody.style.width = valuewidth;
			expbody.style.minWidth = a$.getStyle(expcol, 'width');

			if (a$.isIE || a$.isSafari)
				expbody.style.marginTop = '-1.4em';

			// remove original select
			s.parentNode.removeChild(s);

			// when done perform prep functions
			a$.expcol(div);
			a$.multiSelectPrep(div);
		}
	}
}

a$.selectAll = function(o) {
	var I = a$.T('input', a$.e('a9multiselect-body-'+ o.getAttribute('alt')));
	for (var i = 0, m = I.length; i < m; i++) {
		var c = I[i];
		if (c.type == 'checkbox' && c.className == '_a9checkbox') {
			c.checked = o.checked;
			a$.multiSelect(c.id, c.value, 'a9multiselect-'+ c.getAttribute('alt'));
			a$.chk(c);
		}
	}
}

a$.multiSelect = function(chk, value, parent) {
	var pid = parent.slice('a9multiselect-'.length);
	var to = a$.e(pid);

	chk = a$.isString(chk)? a$.e(chk): chk;
	if (chk.checked) {
		chk.type == 'checkbox'? to.value += a$.msSeparator + value: to.value = value;
	} else
		eval("to.value = to.value.replace(/"+ value +"/g, '');");
	var title = a$.e(parent+'-title');

	// cleans up clogged pipes
	to.value = to.value.replace(/\|{3}/g, a$.msSeparator);
	to.value = to.value.replace(/\|{2}/g, a$.msSeparator);
	to.value = to.value.replace(/^\|(.*)/g, '$1');
	to.value = to.value.replace(/(.*)\|$/g, '$1');

	var cbs = a$.T('input', a$.e('a9multiselect-body-'+ pid)), x = '', v = a$.NO_SELECTION;
	var vals = '', c = 0;
	for (var i = 0, l = cbs.length; i < l; i++)
		if (cbs[i].className == '_a9checkbox' && cbs[i].checked) {
			vals += cbs[i].title +' | ';
			c++;
			if (x == 0) {
				v = cbs[i].title;
			} else {
				v = (x+1) +' '+ a$.SELECTED;
			}
			x++;
		}

	vals = c > 1? vals.slice(0, vals.length-3): v;
	title.innerHTML = v;
	t = a$.e(pid).title;
	title.title =  t == ''? vals: t +' : '+ vals;
}

a$.multiSelectPrep = function(parent) {
	if (parent == null) parent = document;
	var pid = parent.id.slice('a9multiselect-'.length);
	var P = a$.T('input', a$.e('a9multiselect-body-'+ pid)), toObj = a$.e(parent.id.slice('a9multiselect-'.length)), to = toObj.value, newto = '';
	for (var i = 0, l = P.length; i < l; i++) {
		if (P[i].type != null && P[i].className == '_a9checkbox') {
			a$.chk(P[i], false);

			if (P[i].checked == true) {
				a$.chk(P[i]);
				// autoselect and populate the value for default checked items
				var val = P[i].value;
				a$.multiSelect(P[i], val, parent.id);
			}
		}
	}

	if (to != '') { // remove any duplicates when reloading with firefox
		to = to.split(a$.msSeparator).sort();
		for (var i = 1, l = to.length; i < l; i++)
			if (to[i] == to[i-1])
				to[i-1] = null;
		to = to.toString().replace(/,,/g, ',').replace(/,/g, a$.msSeparator);
		toObj.value = to.indexOf(a$.msSeparator) == 0? to.slice(1): to.length > 1 && to.lastIndexOf(a$.msSeparator) == to.length-1? to.slice(0, to.length-1): to;
	}
}

a$.chk = function(c, force) {
	var n = a$.node_after(c);
	if (n != null && n.style) {
		if ((force != null && force) || c.checked) {
			n.style.fontWeight = 'bold';
			if (c.type == 'radio') {
				var R = c.form[c.name];
				for (var i = 0, l = R.length; i < l; i++) {
					var r = R[i];
					if (r.id != c.id)
						a$.node_after(r).style.fontWeight = 'normal';
				}
				a$.expcolclick('a9multiselect-click-'+ c.alt);
			}
		} else {
			n.style.fontWeight = 'normal';
		}
	}
}

a$.closeSelect = function(id) {
	clearTimeout(a$.msBodyTimer);
	a$.msBodyTimer = null;

	var obj = a$.e('a9multiselect-body-'+ id);
	var vis = a$.getStyle(obj, 'display');
	if (vis == 'block') {
		//obj.style.display = 'none';
		a$.expcolclick(a$.e('a9multiselect-click-'+ id));
	}
}

a$.is_ignorable = function(nod) {
  return (nod.nodeType == 8) || // A comment node
         ((nod.nodeType == 3) && !(/[^\t\n\r ]/.test(nod.data))); // a text node, all ws
}

a$.node_before = function(sib) {
	if (a$.isString(sib))
		sib = a$.e(sib);
	while ((sib = sib.previousSibling)) {
		if (!a$.is_ignorable(sib)) return sib;
	}
	return null;
}

a$.node_after = function(sib) {
	while (sib != null && (sib = sib.nextSibling)) {
		if (!a$.is_ignorable(sib)) return sib;
	}
	return null;
}

a$.expcol = function(parent) {
	var x = a$.T("div", parent);
	for (var i = 0, l = x.length; i < l; i++)
		if (x[i].className.indexOf("-click") >= 0) x[i].onclick = a$.expcolclick;
}

a$.expcolclick = function(o, force) {
	var c = null;
	if (a$.isIE)
		var t = this.id? this: a$.isString(o)? a$.e(o): o;
	else
		var t = this.toString().toLowerCase().indexOf('element') >= 0? this: a$.isString(o)? a$.e(o): o;

	c = a$.e('a9multiselect-body-'+ t.id.slice('a9multiselect-click-'.length));
	c.style.position = 'absolute';

	if (c != null && c.style && c.style.display != "block") {
		if (t.className.indexOf("-open") > 0) return;
		t.className = t.className +"-open";
		c.style.display = "block";
		if (force == null || force == false) {
			if (a$.openSelect && a$.openSelect.id != t.id)
				a$.expcolclick(a$.openSelect, true);
			a$.openSelect = t;
		}
	} else if (c != null && c.style) {
		t.className = t.className.substr(0, t.className.length-5);
		c.style.display = "none";
		if (force == null || force == false) {
			a$.openSelect = null;
		}
	}
}

a$.isString = function(o) { return (typeof(o) == "string"); }

/*
	tp: type (eg 'div')
	id: id
	cs: class OR style (if a : exists it is a style (color: pink; display: block;), not a class)
	tx: text to display inside the node
	cd: any child node with which to place inside
	p:  parent node to attach to
*/
a$.newNode = function(tp, id, cs, tx, cd, p) {
	var node = document.createElement(tp);
	if (tx != null && tx != '')
		node.appendChild(document.createTextNode(tx));
	if (id != null && id != '')
		node.id = id;
	if (cs != null && cs != '' && cs.indexOf(':') < 0)
		node.className = cs;
// inline styles removed to limit code to this specific task
//	else if (cs != null && cs != '' && cs.indexOf(':') > 0)
//		a$.setStyles(node, cs);
	if (cd != null)
		node.appendChild(cd);
	if (p != null && p != '')
		(a$.isString(p)? a$.e(p): p).appendChild(node);
	return node;
}

// specific element via id
a$.e = function(id, source) {
	if (source != null)
		return source.getElementById(id);
	return document.getElementById(id);
}

// all elements with tag
a$.T = function(tag, source) {
	if (source != null)
		return source.getElementsByTagName(tag);
	return document.getElementsByTagName(tag);
}

// the first element with tag
a$.t = function(tag, source) {
	if (source != null)
		var T = source.getElementsByTagName(tag);	
	else T = document.getElementsByTagName(tag);
	if (T.length > 0)
		return T[0];
}

// all elements with class
a$.C = function(classname, source) {
	if (source != null)
		return source.getElementsByClassName(classname);
	return document.getElementsByClassName(classname);
}

a$.getStyle = function(obj, styleIE, styleMoz) {
	if (styleMoz == null) styleMoz = styleIE;
	if (a$.isString(obj)) obj = a$.e(obj);
	var s = '';
	if (window.getComputedStyle)
		s = document.defaultView.getComputedStyle(obj, null).getPropertyValue(styleMoz);
	else if (obj.currentStyle)
		s = obj.currentStyle[styleIE];
	if (s == 'auto')
		switch (styleIE) {
		case 'top':		return obj.offsetTop;		break;
		case 'left':	return obj.offsetLeft;		break;
		case 'width':	return obj.offsetWidth;		break;
		case 'height':	return obj.offsetHeight;	break;
		}
	else
		return s;
}

a$.newEvent = function(e, meth, func, cap) {
	if (a$.isString(e))	e = a$.e(e);

	if (e.addEventListener){
		e.addEventListener(meth, func, cap);
    	return true;
	}	else if (e.attachEvent)
		return e.attachEvent("on"+ meth, func);
	return false;
}

// Start things off
a$.newEvent(window, 'load', function () {
	var x = a$.T('select');
	for (var i = 0, l = x.length; i < l; i++) {
		a$.multiSelectCreate(x[i]);
	} 
});

a$.cancelbubble = function(e) {
	if (a$.isIE) e = event;
	if (e) e.cancelBubble = true;
}

function noop() {
	return null;	
}
/**
 * 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 = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            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
        }
        // NOTE 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;
    }
};
/**
 * jGrowl 1.2.0
 *
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Written by Stan Lemon <stanlemon@mac.com>
 * Last updated: 2009.05.11
 *
 * jGrowl is a jQuery plugin implementing unobtrusive userland notifications.  These 
 * notifications function similarly to the Growl Framework available for
 * Mac OS X (http://growl.info).
 *
 * To Do:
 * - Move library settings to containers and allow them to be changed per container
 *
 * Changes in 1.2.0
 * - Added message pooling to limit the number of messages appearing at a given time.
 * - Closing a notification is now bound to the notification object and triggered by the close button.
 *
 * Changes in 1.1.2
 * - Added iPhone styled example
 * - Fixed possible IE7 bug when determining if the ie6 class shoudl be applied.
 * - Added template for the close button, so that it's content could be customized.
 *
 * Changes in 1.1.1
 * - Fixed CSS styling bug for ie6 caused by a mispelling
 * - Changes height restriction on default notifications to min-height
 * - Added skinned examples using a variety of images
 * - Added the ability to customize the content of the [close all] box
 * - Added jTweet, an example of using jGrowl + Twitter
 *
 * Changes in 1.1.0
 * - Multiple container and instances.
 * - Standard $.jGrowl() now wraps $.fn.jGrowl() by first establishing a generic jGrowl container.
 * - Instance methods of a jGrowl container can be called by $.fn.jGrowl(methodName)
 * - Added glue preferenced, which allows notifications to be inserted before or after nodes in the container
 * - Added new log callback which is called before anything is done for the notification
 * - Corner's attribute are now applied on an individual notification basis.
 *
 * Changes in 1.0.4
 * - Various CSS fixes so that jGrowl renders correctly in IE6.
 *
 * Changes in 1.0.3
 * - Fixed bug with options persisting across notifications
 * - Fixed theme application bug
 * - Simplified some selectors and manipulations.
 * - Added beforeOpen and beforeClose callbacks
 * - Reorganized some lines of code to be more readable
 * - Removed unnecessary this.defaults context
 * - If corners plugin is present, it's now customizable.
 * - Customizable open animation.
 * - Customizable close animation.
 * - Customizable animation easing.
 * - Added customizable positioning (top-left, top-right, bottom-left, bottom-right, center)
 *
 * Changes in 1.0.2
 * - All CSS styling is now external.
 * - Added a theme parameter which specifies a secondary class for styling, such
 *   that notifications can be customized in appearance on a per message basis.
 * - Notification life span is now customizable on a per message basis.
 * - Added the ability to disable the global closer, enabled by default.
 * - Added callbacks for when a notification is opened or closed.
 * - Added callback for the global closer.
 * - Customizable animation speed.
 * - jGrowl now set itself up and tears itself down.
 *
 * Changes in 1.0.1:
 * - Removed dependency on metadata plugin in favor of .data()
 * - Namespaced all events
 */
(function($) {

	/** jGrowl Wrapper - Establish a base jGrowl Container for compatibility with older releases. **/
	$.jGrowl = function( m , o ) {
		// To maintain compatibility with older version that only supported one instance we'll create the base container.
		if ( $('#jGrowl').size() == 0 ) $('<div id="jGrowl"></div>').addClass($.jGrowl.defaults.position).appendTo('body');
		// Create a notification on the container.
		$('#jGrowl').jGrowl(m,o);
	};


	/** Raise jGrowl Notification on a jGrowl Container **/
	$.fn.jGrowl = function( m , o ) {
		if ( $.isFunction(this.each) ) {
			var args = arguments;

			return this.each(function() {
				var self = this;

				/** Create a jGrowl Instance on the Container if it does not exist **/
				if ( $(this).data('jGrowl.instance') == undefined ) {
					$(this).data('jGrowl.instance', new $.fn.jGrowl());
					$(this).data('jGrowl.instance').startup( this );
				}

				/** Optionally call jGrowl instance methods, or just raise a normal notification **/
				if ( $.isFunction($(this).data('jGrowl.instance')[m]) ) {
					$(this).data('jGrowl.instance')[m].apply( $(this).data('jGrowl.instance') , $.makeArray(args).slice(1) );
				} else {
					$(this).data('jGrowl.instance').create( m , o );
				}
			});
		};
	};

	$.extend( $.fn.jGrowl.prototype , {

		/** Default JGrowl Settings **/
		defaults: {
			pool: 			0,
			header: 		'',
			group: 			'',
			sticky: 		false,
			position: 		'top-right', // Is this still needed?
			glue: 			'after',
			theme: 			'default',
			corners: 		'10px',
			check: 			250,
			life: 			3000,
			speed: 			'normal',
			easing: 		'swing',
			closer: 		true,
			closeTemplate: '&times;',
			closerTemplate: '<div>[ close all ]</div>',
			log: 			function(e,m,o) {},
			beforeOpen: 	function(e,m,o) {},
			open: 			function(e,m,o) {},
			beforeClose: 	function(e,m,o) {},
			close: 			function(e,m,o) {},
			animateOpen: 	{
				opacity: 	'show'
			},
			animateClose: 	{
				opacity: 	'hide'
			}
		},
		
		notifications: [],
		
		/** jGrowl Container Node **/
		element: 	null,
	
		/** Interval Function **/
		interval:   null,
		
		/** Create a Notification **/
		create: 	function( message , o ) {
			var o = $.extend({}, this.defaults, o);

			this.notifications[ this.notifications.length ] = { message: message , options: o };
			
			o.log.apply( this.element , [this.element,message,o] );
		},
		
		render: 		function( notification ) {
			var self = this;
			var message = notification.message;
			var o = notification.options;

			var notification = $('<div class="jGrowl-notification' + ((o.group != undefined && o.group != '') ? ' ' + o.group : '') + '"><div class="close">' + o.closeTemplate + '</div><div class="header">' + o.header + '</div><div class="message">' + message + '</div></div>')
				.data("jGrowl", o).addClass(o.theme).children('div.close').bind("click.jGrowl", function() {
					$(this).parent().trigger('jGrowl.close');
				}).parent();
				
			( o.glue == 'after' ) ? $('div.jGrowl-notification:last', this.element).after(notification) : $('div.jGrowl-notification:first', this.element).before(notification);

			/** Notification Actions **/
			$(notification).bind("mouseover.jGrowl", function() {
				$(this).data("jGrowl").pause = true;
			}).bind("mouseout.jGrowl", function() {
				$(this).data("jGrowl").pause = false;
			}).bind('jGrowl.beforeOpen', function() {
				o.beforeOpen.apply( self.element , [self.element,message,o] );
			}).bind('jGrowl.open', function() {
				o.open.apply( self.element , [self.element,message,o] );
			}).bind('jGrowl.beforeClose', function() {
				o.beforeClose.apply( self.element , [self.element,message,o] );
			}).bind('jGrowl.close', function() {
				$(this).trigger('jGrowl.beforeClose').animate(o.animateClose, o.speed, o.easing, function() {
					$(this).remove();
					o.close.apply( self.element , [self.element,message,o] );
				});
			}).trigger('jGrowl.beforeOpen').animate(o.animateOpen, o.speed, o.easing, function() {
				$(this).data("jGrowl").created = new Date();
			}).trigger('jGrowl.open');
		
			/** Optional Corners Plugin **/
			if ( $.fn.corner != undefined ) $(notification).corner( o.corners );

			/** Add a Global Closer if more than one notification exists **/
			if ( $('div.jGrowl-notification:parent', this.element).size() > 1 && $('div.jGrowl-closer', this.element).size() == 0 && this.defaults.closer != false ) {
				$(this.defaults.closerTemplate).addClass('jGrowl-closer').addClass(this.defaults.theme).appendTo(this.element).animate(this.defaults.animateOpen, this.defaults.speed, this.defaults.easing).bind("click.jGrowl", function() {
					$(this).siblings().children('div.close').trigger("click.jGrowl");

					if ( $.isFunction( self.defaults.closer ) ) self.defaults.closer.apply( $(this).parent()[0] , [$(this).parent()[0]] );
				});
			};
		},

		/** Update the jGrowl Container, removing old jGrowl notifications **/
		update:	 function() {
			$(this.element).find('div.jGrowl-notification:parent').each( function() {
				if ( $(this).data("jGrowl") != undefined && $(this).data("jGrowl").created != undefined && ($(this).data("jGrowl").created.getTime() + $(this).data("jGrowl").life)  < (new Date()).getTime() && $(this).data("jGrowl").sticky != true && 
					 ($(this).data("jGrowl").pause == undefined || $(this).data("jGrowl").pause != true) ) {
					$(this).trigger('jGrowl.close');
				}
			});

			if ( this.notifications.length > 0 && (this.defaults.pool == 0 || $(this.element).find('div.jGrowl-notification:parent').size() < this.defaults.pool) ) {
				this.render( this.notifications.shift() );
			}

			if ( $(this.element).find('div.jGrowl-notification:parent').size() < 2 ) {
				$(this.element).find('div.jGrowl-closer').animate(this.defaults.animateClose, this.defaults.speed, this.defaults.easing, function() {
					$(this).remove();
				});
			};
		},

		/** Setup the jGrowl Notification Container **/
		startup:	function(e) {
			this.element = $(e).addClass('jGrowl').append('<div class="jGrowl-notification"></div>');
			this.interval = setInterval( function() { 
				jQuery(e).data('jGrowl.instance').update(); 
			}, this.defaults.check);
			
			if ($.browser.msie && parseInt($.browser.version) < 7 && !window["XMLHttpRequest"]) $(this.element).addClass('ie6');
		},

		/** Shutdown jGrowl, removing it and clearing the interval **/
		shutdown:   function() {
			$(this.element).removeClass('jGrowl').find('div.jGrowl-notification').remove();
			clearInterval( this.interval );
		}
	});
	
	/** Reference the Defaults Object for compatibility with older versions of jGrowl **/
	$.jGrowl.defaults = $.fn.jGrowl.prototype.defaults;

})(jQuery);
/*
 * JQZoom Evolution 1.0.1 - Javascript Image magnifier
 *
 * Copyright (c) Engineer Renzi Marco(www.mind-projects.it)
 *
 * $Date: 12-12-2008
 *
 *	ChangeLog:
 *  
 * $License : GPL,so any change to the code you should copy and paste this section,and would be nice to report this to me(renzi.mrc@gmail.com).
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(6($){$.30.31=6(G){I H={17:\'32\',18:2l,19:2l,1a:10,1b:0,Q:"2m",2n:1s,2o:12,2p:0.3,14:1s,1p:12,2q:\'1g\',2r:\'23\',2s:\'24\',2t:\'33\',2u:12,2v:1s,2w:\'34 35\',2x:\'1t\'};G=G||{};$.36(H,G);R 4.37(6(){I a=$(4);I d=a.1q(\'14\');$(a).1Q(\'14\');$(a).J(\'38-K\',\'1r\');$(a).J(\'39-3a\',\'1r\');I f=$(a).1q(\'3b\');I g=$("1H",4);I j=g.1q(\'14\');g.1Q(\'14\');I k=U 25(g);I l={};I m=0;I n=0;I p=1u;p=U 1R();I q=(26(d).Y>0)?d:(26(j).Y>0)?j:1u;I r=U 27();I s=U 1v(a[0].2y);I t=U 1c();I u={};I v=12;I y={};I z=1u;I A=12;I B={};I C=0;I D=12;I E=12;I F=12;k.1I();$(4).3c(6(){R 12});$(4).3d(6(e){B.x=e.1w;B.y=e.1x;k.1S();1d()},6(){k.1S();2z()});8(H.1p){2A(6(){1d()},3e)}6 1d(){8(!A){k.28();A=1s;j=g.1q(\'14\');g.1Q(\'14\');d=a.1q(\'14\');$(a).1Q(\'14\');s=U 1v(a[0].2y);8(!v||$.1e.2B){s.1I()}V{8(H.17!=\'1j\'){z=U 1J();z.1d()}t=U 1c;t.1d()}a[0].3f();R 12}};6 2z(){8(H.17==\'1K\'&&!H.1p){g.J({\'1T\':1})}8(!H.1p){A=12;v=12;$(t.5).29(\'1L\');t.Z();8($(\'P.1M\').Y>0){z.Z()}8($(\'P.2a\').Y>0){r.Z()}g.1q(\'14\',j);a.1q(\'14\',d);$().29();a.29(\'1L\');C=0;8(1y(\'.2b\').Y>0){1y(\'.2b\').Z()}}V{8(H.2o){1k(H.17){11\'1j\':s.2c();N;1l:t.1t();N}}}8(H.1p){1d()}};6 25(c){4.5=c[0];4.1I=6(){4.5.1m=c[0].1m};4.28=6(){I a=\'\';a=$(g).J(\'2C-L-W\');m=\'\';I b=\'\';b=$(g).J(\'2C-M-W\');n=\'\';8(a){1U(i=0;i<3;i++){I x=[];x=a.1n(i,1);8(1V(x)==12){m=m+\'\'+a.1n(i,1)}V{N}}}8(b){1U(i=0;i<3;i++){8(!1V(b.1n(i,1))){n=n+b.1n(i,1)}V{N}}}m=(m.Y>0)?1W(m):0;n=(n.Y>0)?1W(n):0};4.5.2D=6(){a.J({\'2E\':\'2F\',\'1h\':\'1X\'});8(a.J(\'Q\')!=\'15\'&&a.2d().J(\'Q\')){a.J({\'2E\':\'2F\',\'Q\':\'2G\',\'1h\':\'1X\'})}8(a.2d().J(\'Q\')!=\'15\'){a.2d().J(\'Q\',\'2G\')}V{}8($.1e.2B||$.1e.3g){$(g).J({Q:\'15\',L:\'2H\',M:\'2H\'})}l.w=$(4).W();l.h=$(4).1f();l.9=$(4).1i();l.9.l=$(4).1i().M;l.9.t=$(4).1i().L;l.9.r=l.w+l.9.l;l.9.b=l.h+l.9.t;a.1f(l.h);a.W(l.w);8(H.2u){k.1S();s.1I()}};R 4};25.13.1S=6(){l.9=$(g).1i();l.9.l=$(g).1i().M;l.9.t=$(g).1i().L;l.9.r=l.w+l.9.l;l.9.b=l.h+l.9.t};6 1c(){4.5=16.2e("P");$(4.5).1Y(\'X\');4.5.3h=6(){$(t.5).Z();t=U 1c();t.1d()};4.2I=6(){1k(H.17){11\'1K\':4.1z=U 1Z();4.1z.1m=k.5.1m;4.5.1N(4.1z);$(4.5).J({\'1T\':1});N;11\'1j\':4.1z=U 1Z();4.1z.1m=s.5.1m;4.5.1N(4.1z);$(4.5).J({\'1T\':1});N;1l:N}1k(H.17){11\'1j\':u.w=l.w;u.h=l.h;N;1l:u.w=(H.18)/y.x;u.h=(H.19)/y.y;N}$(4.5).J({W:u.w+\'S\',1f:u.h+\'S\',Q:\'15\',1h:\'1r\',3i:1+\'S\'});a.3j(4.5)};R 4};1c.13.1d=6(){4.2I();1k(H.17){11\'1K\':g.J({\'1T\':H.2p});(H.1p)?t.1t():t.1o(1u);a.2f(\'1L\',6(e){B.x=e.1w;B.y=e.1x;t.1o(e)});N;11\'1j\':$(4.5).J({L:0,M:0});8(H.14){r.2g()}s.2c();a.2f(\'1L\',6(e){B.x=e.1w;B.y=e.1x;s.2J(e)});N;1l:(H.1p)?t.1t():t.1o(1u);$(a).2f(\'1L\',6(e){B.x=e.1w;B.y=e.1x;t.1o(e)});N}R 4};1c.13.1o=6(e){8(e){B.x=e.1w;B.y=e.1x}8(C==0){I b=(l.w)/2-(u.w)/2;I c=(l.h)/2-(u.h)/2;$(\'P.X\').1g();8(H.2n){4.5.K.20=\'2K\'}V{4.5.K.20=\'2h\';$(\'P.X\').23()}C=1}V{I b=B.x-l.9.l-(u.w)/2;I c=B.y-l.9.t-(u.h)/2}8(2L()){b=0+n}V 8(2M()){8($.1e.1O&&$.1e.2i<7){b=l.w-u.w+n-1}V{b=l.w-u.w+n-1}}8(2N()){c=0+m}V 8(2O()){8($.1e.1O&&$.1e.2i<7){c=l.h-u.h+m-1}V{c=l.h-u.h-1+m}}b=1A(b);c=1A(c);$(\'P.X\',a).J({L:c,M:b});8(H.17==\'1K\'){$(\'P.X 1H\',a).J({\'Q\':\'15\',\'L\':-(c-m+1),\'M\':-(b-n+1)})}4.5.K.M=b+\'S\';4.5.K.L=c+\'S\';s.1o();6 2L(){R B.x-(u.w+2*1)/2-n<l.9.l}6 2M(){R B.x+(u.w+2*1)/2>l.9.r+n}6 2N(){R B.y-(u.h+2*1)/2-m<l.9.t}6 2O(){R B.y+(u.h+2*1)/2>l.9.b+m}R 4};1c.13.1t=6(){$(\'P.X\',a).J(\'1h\',\'1r\');I b=(l.w)/2-(u.w)/2;I c=(l.h)/2-(u.h)/2;4.5.K.M=b+\'S\';4.5.K.L=c+\'S\';$(\'P.X\',a).J({L:c,M:b});8(H.17==\'1K\'){$(\'P.X 1H\',a).J({\'Q\':\'15\',\'L\':-(c-m+1),\'M\':-(b-n+1)})}s.1o();8($.1e.1O){$(\'P.X\',a).1g()}V{2A(6(){$(\'P.X\').2P(\'24\')},10)}};1c.13.1P=6(){I o={};o.M=1A(4.5.K.M);o.L=1A(4.5.K.L);R o};1c.13.Z=6(){8(H.17==\'1j\'){$(\'P.X\',a).2Q(\'24\',6(){$(4).Z()})}V{$(\'P.X\',a).Z()}};1c.13.28=6(){I a=\'\';a=$(\'P.X\').J(\'3k\');1B=\'\';I b=\'\';b=$(\'P.X\').J(\'3l\');1C=\'\';8($.1e.1O){I c=a.2R(\' \');a=c[1];I c=b.2R(\' \');b=c[1]}8(a){1U(i=0;i<3;i++){I x=[];x=a.1n(i,1);8(1V(x)==12){1B=1B+\'\'+a.1n(i,1)}V{N}}}8(b){1U(i=0;i<3;i++){8(!1V(b.1n(i,1))){1C=1C+b.1n(i,1)}V{N}}}1B=(1B.Y>0)?1W(1B):0;1C=(1C.Y>0)?1W(1C):0};6 1v(a){4.2S=a;4.5=U 1Z();4.1I=6(){8(!4.5)4.5=U 1Z();4.5.K.Q=\'15\';4.5.K.1h=\'1r\';4.5.K.M=\'-3m\';4.5.K.L=\'3n\';p=U 1R();8(H.2v&&!D){p.1g();D=1s}16.2j.1N(4.5);4.5.1m=4.2S};4.5.2D=6(){4.K.1h=\'1X\';I w=O.21($(4).W());I h=O.21($(4).1f());4.K.1h=\'1r\';y.x=(w/l.w);y.y=(h/l.h);8($(\'P.1D\').Y>0){$(\'P.1D\').Z()}v=1s;8(H.17!=\'1j\'&&A){z=U 1J();z.1d()}8(A){t=U 1c();t.1d()}8($(\'P.1D\').Y>0){$(\'P.1D\').Z()}};R 4};1v.13.1o=6(){4.5.K.M=O.1E(-y.x*1A(t.1P().M)+n)+\'S\';4.5.K.L=O.1E(-y.y*1A(t.1P().L)+m)+\'S\'};1v.13.2J=6(e){4.5.K.M=O.1E(-y.x*O.T(e.1w-l.9.l))+\'S\';4.5.K.L=O.1E(-y.y*O.T(e.1x-l.9.t))+\'S\';$(\'P.X 1H\',a).J({\'Q\':\'15\',\'L\':4.5.K.L,\'M\':4.5.K.M})};1v.13.2c=6(){4.5.K.M=O.1E(-y.x*O.T((l.w)/2))+\'S\';4.5.K.L=O.1E(-y.y*O.T((l.h)/2))+\'S\';$(\'P.X 1H\',a).J({\'Q\':\'15\',\'L\':4.5.K.L,\'M\':4.5.K.M})};6 1J(){I a=1y(g).1i().M;I b=1y(g).1i().L;4.5=16.2e("P");$(4.5).1Y(\'1M\');$(4.5).J({Q:\'15\',W:O.21(H.18)+\'S\',1f:O.21(H.19)+\'S\',1h:\'1r\',2T:3o,3p:\'2h\'});1k(H.Q){11"2m":a=(a+$(g).W()+O.T(H.1a)+H.18<$(16).W())?(a+$(g).W()+O.T(H.1a)):(a-H.18-10);1F=b+H.1b+H.19;b=(1F<$(16).1f()&&1F>0)?b+H.1b:b;N;11"M":a=(l.9.l-O.T(H.1a)-H.18>0)?(l.9.l-O.T(H.1a)-H.18):(l.9.l+l.w+10);1F=l.9.t+H.1b+H.19;b=(1F<$(16).1f()&&1F>0)?l.9.t+H.1b:l.9.t;N;11"L":b=(l.9.t-O.T(H.1b)-H.19>0)?(l.9.t-O.T(H.1b)-H.19):(l.9.t+l.h+10);1G=l.9.l+H.1a+H.18;a=(1G<$(16).W()&&1G>0)?l.9.l+H.1a:l.9.l;N;11"3q":b=(l.9.b+O.T(H.1b)+H.19<$(16).1f())?(l.9.b+O.T(H.1b)):(l.9.t-H.19-10);1G=l.9.l+H.1a+H.18;a=(1G<$(16).W()&&1G>0)?l.9.l+H.1a:l.9.l;N;1l:a=(l.9.l+l.w+H.1a+H.18<$(16).W())?(l.9.l+l.w+O.T(H.1a)):(l.9.l-H.18-O.T(H.1a));b=(l.9.b+O.T(H.1b)+H.19<$(16).1f())?(l.9.b+O.T(H.1b)):(l.9.t-H.19-O.T(H.1b));N}4.5.K.M=a+\'S\';4.5.K.L=b+\'S\';R 4};1J.13.1d=6(){8(!4.5.3r)4.5.1N(s.5);8(H.14){r.2g()}16.2j.1N(4.5);1k(H.2q){11\'1g\':$(4.5).1g();N;11\'3s\':$(4.5).2P(H.2s);N;1l:$(4.5).1g();N}$(4.5).1g();8($.1e.1O&&$.1e.2i<7){4.3t=$(\'<2U 3u="2b" 3v="3w" 3x="0"  1m="#"  K="3y-3z: 2V" 3A="2V"></2U>\').J({Q:"15",M:4.5.K.M,L:4.5.K.L,2T:3B,W:(H.18+2),1f:(H.19)}).3C(4.5)};s.5.K.1h=\'1X\'};1J.13.Z=6(){1k(H.2r){11\'23\':$(\'.1M\').Z();N;11\'3D\':$(\'.1M\').2Q(H.2t);N;1l:$(\'.1M\').Z();N}};6 27(){4.5=1y(\'<P />\').1Y(\'2a\').2W(\'\'+q+\'\');4.2g=6(){8(H.17==\'1j\'){$(4.5).J({Q:\'15\',L:l.9.b+3,M:(l.9.l+1),W:l.w}).2k(\'2j\')}V{$(4.5).2k(z.5)}}};27.13.Z=6(){$(\'.2a\').Z()};6 1R(){4.5=16.2e("P");$(4.5).1Y(\'1D\');$(4.5).2W(H.2w);$(4.5).2k(a).J(\'20\',\'2h\');4.1g=6(){1k(H.2x){11\'1t\':2X=(l.h-$(4.5).1f())/2;2Y=(l.w-$(4.5).W())/2;$(4.5).J({L:2X,M:2Y});N;1l:I a=4.1P();N}$(4.5).J({Q:\'15\',20:\'2K\'})};R 4};1R.13.1P=6(){I o=1u;o=$(\'P.1D\').1i();R o}})}})(1y);6 26(a){2Z(a.22(0,1)==\' \'){a=a.22(1,a.Y)}2Z(a.22(a.Y-1,a.Y)==\' \'){a=a.22(0,a.Y-1)}R a};',62,226,'||||this|node|function||if|pos|||||||||||||||||||||||||||||||||||var|css|style|top|left|break|Math|div|position|return|px|abs|new|else|width|jqZoomPup|length|remove||case|false|prototype|title|absolute|document|zoomType|zoomWidth|zoomHeight|xOffset|yOffset|Lens|activate|browser|height|show|display|offset|innerzoom|switch|default|src|substr|setposition|alwaysOn|attr|none|true|center|null|Largeimage|pageX|pageY|jQuery|image|parseInt|lensbtop|lensbleft|preload|ceil|topwindow|leftwindow|img|loadimage|Stage|reverse|mousemove|jqZoomWindow|appendChild|msie|getoffset|removeAttr|Loader|setpos|opacity|for|isNaN|eval|block|addClass|Image|visibility|round|substring|hide|fast|Smallimage|trim|zoomTitle|findborder|unbind|jqZoomTitle|zoom_ieframe|setcenter|parent|createElement|bind|loadtitle|hidden|version|body|appendTo|200|right|lens|lensReset|imageOpacity|showEffect|hideEffect|fadeinSpeed|fadeoutSpeed|preloadImages|showPreload|preloadText|preloadPosition|href|deactivate|setTimeout|safari|border|onload|cursor|crosshair|relative|0px|loadlens|setinner|visible|overleft|overright|overtop|overbottom|fadeIn|fadeOut|split|url|zIndex|iframe|transparent|html|loadertop|loaderleft|while|fn|jqzoom|standard|slow|Loading|zoom|extend|each|outline|text|decoration|rel|click|hover|150|blur|opera|onerror|borderWidth|append|borderTop|borderLeft|5000px|10px|10000|overflow|bottom|firstChild|fadein|ieframe|class|name|content|frameborder|background|color|bgcolor|99|insertBefore|fadeout'.split('|'),0,{}))
ï»¿/**
 * jQuery.timers - Timer abstractions for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/02/08
 *
 * @author Blair Mitchelmore
 * @version 1.1.2
 *
 **/

jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.event.special

jQuery.extend({
	timer: {
		global: [],
		guid: 1,
		dataKey: "jQuery.timer",
		regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
				return;

			if (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}
			
			times = times || 0;
			belay = belay || false;
			
			var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
			
			if (!timers[label])
				timers[label] = {};
			
			fn.timerID = fn.timerID || this.guid++;
			
			var handler = function() {
				if (belay && this.inProgress) 
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};
			
			handler.timerID = fn.timerID;
			
			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,interval);
			
			this.global.push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.timerID ) {
							window.clearInterval(timers[label][fn.timerID]);
							delete timers[label][fn.timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					jQuery.removeData(element, this.dataKey);
			}
		}
	}
});

jQuery(window).bind("unload", function() {
	jQuery.each(jQuery.timer.global, function(index, item) {
		jQuery.timer.remove(item);
	});
});
/*

    GalleryView - jQuery Content Gallery Plugin
    Author:         Jack Anderson
    Version:        2.0 (May 5, 2009)
    Documentation:     http://www.spaceforaname.com/galleryview/
    
    Please use this development script if you intend to make changes to the
    plugin code.  For production sites, please use jquery.galleryview-2.0-pack.js.
    
    See CHANGELOG.txt for a review of changes and LICENSE.txt for the applicable
    licensing information.


*/

//Global variable to check if window is already loaded
//Used for calling GalleryView after page has loaded
var window_loaded = false;
            
(function($){
    $.fn.galleryView = function(options) {
        var opts = $.extend($.fn.galleryView.defaults,options);
        
        var id;
        var iterator = 0;
        var item_count = 0;
        var slide_method;
        var theme_path;
        var paused = false;
        
        //Element dimensions
        var gallery_width;
        var gallery_height;
        var pointer_height;
        var pointer_width;
        var strip_width;
        var strip_height;
        var wrapper_width;
        var f_frame_width;
        var f_frame_height;
        var frame_caption_size = 20;
        var gallery_padding;
        var filmstrip_margin;
        var filmstrip_orientation;
        
        
        //Arrays used to scale frames and panels
        var frame_img_scale = new Object();
        var panel_img_scale = new Object();
        var img_h = new Object();
        var img_w = new Object();
        
        //Flag indicating whether to scale panel images
        var scale_panel_images = true;
        
        var panel_nav_displayed = false;
        
        //Define jQuery objects for reuse
        var j_gallery;
        var j_filmstrip;
        var j_frames;
        var j_frame_img_wrappers;
        var j_panels;
        var j_pointer;
        
        
/************************************************/
/*    Plugin Methods                                */
/************************************************/    

    //Transition from current item to item 'i'
        function showItem(i) {
        
            //Disable next/prev buttons until transition is complete
            $('.nav-next-overlay',j_gallery).unbind('click');
            $('.nav-prev-overlay',j_gallery).unbind('click');
            $('.nav-next',j_gallery).unbind('click');
            $('.nav-prev',j_gallery).unbind('click');
            j_frames.unbind('click');
            
            //Fade out all frames while fading in target frame
            if(opts.show_filmstrip) {
                j_frames.removeClass('current').find('img').stop().animate({
                    'opacity':opts.frame_opacity
                },opts.transition_speed);
                j_frames.eq(i).addClass('current').find('img').stop().animate({
                    'opacity':1.0
                },opts.transition_speed);
            }
            
            //If the gallery has panels and the panels should fade, fade out all panels while fading in target panel
            if(opts.show_panels && opts.fade_panels) {
                j_panels.fadeOut(opts.transition_speed).eq(i%item_count).fadeIn(opts.transition_speed,function(){
                    if(!opts.show_filmstrip) {
                        $('.nav-prev-overlay',j_gallery).click(showPrevItem);
                        $('.nav-next-overlay',j_gallery).click(showNextItem);
                        $('.nav-prev',j_gallery).click(showPrevItem);
                        $('.nav-next',j_gallery).click(showNextItem);        
                    }
                });
            }
            
            //If gallery has a filmstrip, handle animation of frames
            if(opts.show_filmstrip) {
                //Slide either pointer or filmstrip, depending on transition method
                if(slide_method=='strip') {
                    //Stop filmstrip if it's currently in motion
                    j_filmstrip.stop();
                    
                    if(filmstrip_orientation=='horizontal') {
                        //Determine distance between pointer (eventual destination) and target frame
                        var distance = getPos(j_frames[i]).left - (getPos(j_pointer[0]).left+(pointer_width/2)-(f_frame_width/2));
                        var diststr = (distance>=0?'-=':'+=')+Math.abs(distance)+'px';
                        
                        //Animate filmstrip and slide target frame under pointer
                        j_filmstrip.animate({
                            'left':diststr
                        },opts.transition_speed,opts.easing,function(){
                            //Always ensure that there are a sufficient number of hidden frames on either
                            //side of the filmstrip to avoid empty frames
                            var old_i = i;
                            if(i>item_count) {
                                i = i%item_count;
                                iterator = i;
                                j_filmstrip.css('left','-'+((f_frame_width+opts.frame_gap)*i)+'px');
                            } else if (i<=(item_count-strip_size)) {
                                i = (i%item_count)+item_count;
                                iterator = i;
                                j_filmstrip.css('left','-'+((f_frame_width+opts.frame_gap)*i)+'px');
                            }
                            //If the target frame has changed due to filmstrip shifting,
                            //Make sure new target frame has 'current' class and correct size/opacity settings
                            if(old_i != i) {
                                j_frames.eq(old_i).removeClass('current').find('img').css({
                                    'opacity':opts.frame_opacity
                                });
                                j_frames.eq(i).addClass('current').find('img').css({
                                    'opacity':1.0
                                });
                            }
                            if(!opts.fade_panels) {
                                j_panels.hide().eq(i%item_count).show();
                            }
                            
                            //Enable navigation now that animation is complete
                            $('.nav-prev-overlay',j_gallery).click(showPrevItem);
                            $('.nav-next-overlay',j_gallery).click(showNextItem);
                            $('.nav-prev',j_gallery).click(showPrevItem);
                            $('.nav-next',j_gallery).click(showNextItem);
                            enableFrameClicking();
                        });
                    } else {
                        //Determine distance between pointer (eventual destination) and target frame
                        var distance = getPos(j_frames[i]).top - (getPos(j_pointer[0]).top+(pointer_height)-(f_frame_height/2));
                        var diststr = (distance>=0?'-=':'+=')+Math.abs(distance)+'px';
                        
                        //Animate filmstrip and slide target frame under pointer
                        j_filmstrip.animate({
                            'top':diststr
                        },opts.transition_speed,opts.easing,function(){
                            //Always ensure that there are a sufficient number of hidden frames on either
                            //side of the filmstrip to avoid empty frames
                            var old_i = i;
                            if(i>item_count) {
                                i = i%item_count;
                                iterator = i;
                                j_filmstrip.css('top','-'+((f_frame_height+opts.frame_gap)*i)+'px');
                            } else if (i<=(item_count-strip_size)) {
                                i = (i%item_count)+item_count;
                                iterator = i;
                                j_filmstrip.css('top','-'+((f_frame_height+opts.frame_gap)*i)+'px');
                            }
                            //If the target frame has changed due to filmstrip shifting,
                            //Make sure new target frame has 'current' class and correct size/opacity settings
                            if(old_i != i) {
                                j_frames.eq(old_i).removeClass('current').find('img').css({
                                    'opacity':opts.frame_opacity
                                });
                                j_frames.eq(i).addClass('current').find('img').css({
                                    'opacity':1.0
                                });
                            }
                            if(!opts.fade_panels) {
                                j_panels.hide().eq(i%item_count).show();
                            }
                            
                            //Enable navigation now that animation is complete
                            $('.nav-prev-overlay',j_gallery).click(showPrevItem);
                            $('.nav-next-overlay',j_gallery).click(showNextItem);
                            $('.nav-prev',j_gallery).click(showPrevItem);
                            $('.nav-next',j_gallery).click(showNextItem);
                            enableFrameClicking();
                        });
                    }
                } else if(slide_method=='pointer') {
                    //Stop pointer if it's currently in motion
                    j_pointer.stop();
                    //Get position of target frame
                    var pos = getPos(j_frames[i]);
                    
                    if(filmstrip_orientation=='horizontal') {
                        //Slide the pointer over the target frame
                        j_pointer.animate({
                            'left':(pos.left+(f_frame_width/2)-(pointer_width/2)+'px')
                        },opts.transition_speed,opts.easing,function(){    
                            if(!opts.fade_panels) {
                                j_panels.hide().eq(i%item_count).show();
                            }    
                            $('.nav-prev-overlay',j_gallery).click(showPrevItem);
                            $('.nav-next-overlay',j_gallery).click(showNextItem);
                            $('.nav-prev',j_gallery).click(showPrevItem);
                            $('.nav-next',j_gallery).click(showNextItem);
                            enableFrameClicking();
                        });
                    } else {//Slide the pointer over the target frame
                        j_pointer.animate({
                            'top':(pos.top+(f_frame_height/2)-(pointer_height)+'px')
                        },opts.transition_speed,opts.easing,function(){    
                            if(!opts.fade_panels) {
                                j_panels.hide().eq(i%item_count).show();
                            }    
                            $('.nav-prev-overlay',j_gallery).click(showPrevItem);
                            $('.nav-next-overlay',j_gallery).click(showNextItem);
                            $('.nav-prev',j_gallery).click(showPrevItem);
                            $('.nav-next',j_gallery).click(showNextItem);
                            enableFrameClicking();
                        });
                    }
                }
            
            }
        };
        
    //Find padding and border widths applied to element
    //If border is non-numerical ('thin','medium', etc) set to zero
        function extraWidth(el) {
            if(!el) return 0;
            if(el.length==0) return 0;
            el = el.eq(0);
            var ew = 0;
            ew += getInt(el.css('paddingLeft'));
            ew += getInt(el.css('paddingRight'));
            ew += getInt(el.css('borderLeftWidth'));
            ew += getInt(el.css('borderRightWidth'));
            return ew;
        }
    //Find padding and border heights applied to element
    //If border is non-numerical ('thin','medium', etc) set to zero
        function extraHeight(el) {
            if(!el) return 0;
            if(el.length==0) return 0;
            el = el.eq(0);
            var eh = 0;
            eh += getInt(el.css('paddingTop'));
            eh += getInt(el.css('paddingBottom'));
            eh += getInt(el.css('borderTopWidth'));
            eh += getInt(el.css('borderBottomWidth'));
            return eh;
        }
        
    //Halt transition timer, move to next item, restart timer
        function showNextItem() {
            
            $(document).stopTime("transition");
            if(++iterator==j_frames.length) {iterator=0;}
            showItem(iterator);
            if(!paused) {
                $(document).everyTime(opts.transition_interval,"transition",function(){
                    showNextItem();
                });
            }
        };
        
    //Halt transition timer, move to previous item, restart timer
        function showPrevItem() {
            $(document).stopTime("transition");
            if(--iterator<0) {iterator = item_count-1;}
            showItem(iterator);
            if(!paused) {
                $(document).everyTime(opts.transition_interval,"transition",function(){
                    showNextItem();
                });
            }
        };
        
    //Get absolute position of element in relation to top-left corner of gallery
    //If el=gallery, return position of gallery within browser viewport
        function getPos(el) {
            var left = 0, top = 0;
            var el_id = el.id;
            if(el.offsetParent) {
                do {
                    left += el.offsetLeft;
                    top += el.offsetTop;
                } while(el = el.offsetParent);
            }
            //If we want the position of the gallery itself, return it
            if(el_id == id) {return {'left':left,'top':top};}
            //Otherwise, get position of element relative to gallery
            else {
                var gPos = getPos(j_gallery[0]);
                var gLeft = gPos.left;
                var gTop = gPos.top;
                
                return {'left':left-gLeft,'top':top-gTop};
            }
        };
        
    //Add onclick event to each frame
        function enableFrameClicking() {
            j_frames.each(function(i){
                //If there isn't a link in this frame, set up frame to slide on click
                //Frames with links will handle themselves
                if($('a',this).length==0) {
                    $(this).click(function(){
                        if(iterator!=i) {
                            $(document).stopTime("transition");
                            showItem(i);
                            iterator = i;
                            if(!paused) {
                                $(document).everyTime(opts.transition_interval,"transition",function(){
                                    showNextItem();
                                });
                            }
                        }
                    });
                }
            });
        };
        
    //Construct gallery panels from '.panel' <div>s
        function buildPanels() {
            //If there are panel captions, add overlay divs
            j_panels.each(function(i){
                   if($('.panel-overlay',this).length>0) {
                    $(this).append('<div class="overlay-background"></div>');    
                }
               });
            if(!opts.show_filmstrip) {
                //Add navigation buttons
                $('<img />').addClass('nav-next').attr('src',theme_path+opts.nav_theme+'/next.gif').appendTo(j_gallery).css({
                    'position':'absolute',
                    'zIndex':'1100',
                    'cursor':'pointer',
                    'top':((opts.panel_height-22)/2)+gallery_padding+'px',
                    'right':'10px',
                    'display':'none'
                }).click(showNextItem);
                $('<img />').addClass('nav-prev').attr('src',theme_path+opts.nav_theme+'/prev.gif').appendTo(j_gallery).css({
                    'position':'absolute',
                    'zIndex':'1100',
                    'cursor':'pointer',
                    'top':((opts.panel_height-22)/2)+gallery_padding+'px',
                    'left':'10px',
                    'display':'none'
                }).click(showPrevItem);
                
                $('<img />').addClass('nav-next-overlay').attr('src',theme_path+opts.nav_theme+'/panel-nav-next.gif').appendTo(j_gallery).css({
                    'position':'absolute',
                    'zIndex':'1099',
                    'top':((opts.panel_height-22)/2)+gallery_padding-10+'px',
                    'right':'0',
                    'display':'none',
                    'cursor':'pointer',
                    'opacity':0.75
                }).click(showNextItem);
                
                $('<img />').addClass('nav-prev-overlay').attr('src',theme_path+opts.nav_theme+'/panel-nav-prev.gif').appendTo(j_gallery).css({
                    'position':'absolute',
                    'zIndex':'1099',
                    'top':((opts.panel_height-22)/2)+gallery_padding-10+'px',
                    'left':'0',
                    'display':'none',
                    'cursor':'pointer',
                    'opacity':0.75
                }).click(showPrevItem);
            }
            j_panels.each(function(i){
                $(this).css({
                    'width':(opts.panel_width-extraWidth(j_panels))+'px',
                    'height':(opts.panel_height-extraHeight(j_panels))+'px',
                    'position':'absolute',
                    'overflow':'hidden',
                    'display':'none'
                });
                switch(opts.filmstrip_position) {
                    case 'top': $(this).css({
                                    'top':strip_height+Math.max(gallery_padding,filmstrip_margin)+'px',
                                    'left':gallery_padding+'px'
                                }); break;
                    case 'left': $(this).css({
                                     'top':gallery_padding+'px',
                                    'left':strip_width+Math.max(gallery_padding,filmstrip_margin)+'px'
                                 }); break;
                    default: $(this).css({'top':gallery_padding+'px','left':gallery_padding+'px'}); break;
                }
            });
            $('.panel-overlay',j_panels).css({
                'position':'absolute',
                'zIndex':'999',
                'width':(opts.panel_width-extraWidth($('.panel-overlay',j_panels)))+'px',
                'left':'0'
            });
            $('.overlay-background',j_panels).css({
                'position':'absolute',
                'zIndex':'998',
                'width':opts.panel_width+'px',
                'left':'0',
                'opacity':opts.overlay_opacity
            });
            if(opts.overlay_position=='top') {
                $('.panel-overlay',j_panels).css('top',0);
                $('.overlay-background',j_panels).css('top',0);
            } else {
                $('.panel-overlay',j_panels).css('bottom',0);
                $('.overlay-background',j_panels).css('bottom',0);
            }
            
            $('.panel iframe',j_panels).css({
                'width':opts.panel_width+'px',
                'height':opts.panel_height+'px',
                'border':'0'
            });
            
            if(scale_panel_images) {
                $('img',j_panels).each(function(i){
                    $(this).css({
                        'height':panel_img_scale[i%item_count]*img_h[i%item_count],
                        'width':panel_img_scale[i%item_count]*img_w[i%item_count],
                        'position':'relative',
                        'top':(opts.panel_height-(panel_img_scale[i%item_count]*img_h[i%item_count]))/2+'px',
                        'left':(opts.panel_width-(panel_img_scale[i%item_count]*img_w[i%item_count]))/2+'px'
                    });
                });
            }
        };
        
    //Construct filmstrip from '.filmstrip' <ul>
        function buildFilmstrip() {
            //Add wrapper to filmstrip to hide extra frames
            j_filmstrip.wrap('<div class="strip_wrapper"></div>');
            if(slide_method=='strip') {
                j_frames.clone().appendTo(j_filmstrip);
                j_frames.clone().appendTo(j_filmstrip);
                j_frames = $('li',j_filmstrip);
            }
            //If captions are enabled, add caption divs and fill with the image titles
            if(opts.show_captions) {
                j_frames.append('<div class="caption"></div>').each(function(i){
                    $(this).find('.caption').html($(this).find('img').attr('title'));    
                    //$(this).find('.caption').html(i);        
                });
            }
            j_filmstrip.css({
                'listStyle':'none',
                'margin':'0',
                'padding':'0',
                'width':strip_width+'px',
                'position':'absolute',
                'zIndex':'900',
                'top':(filmstrip_orientation=='vertical' && slide_method=='strip'?-((f_frame_height+opts.frame_gap)*iterator):0)+'px',
                'left':(filmstrip_orientation=='horizontal' && slide_method=='strip'?-((f_frame_width+opts.frame_gap)*iterator):0)+'px',
                'height':strip_height+'px'
            });
            j_frames.css({
                'float':'left',
                'position':'relative',
                'height':f_frame_height+(opts.show_captions?frame_caption_size:0)+'px',
                'width':f_frame_width+'px',
                'zIndex':'901',
                'padding':'0',
                'cursor':'pointer'
            });
            switch(opts.filmstrip_position) {
                case 'top': j_frames.css({
                                'marginBottom':filmstrip_margin+'px',
                                'marginRight':opts.frame_gap+'px'
                            }); break;
                case 'bottom': j_frames.css({
                                'marginTop':filmstrip_margin+'px',
                                'marginRight':opts.frame_gap+'px'
                            }); break;
                case 'left': j_frames.css({
                                'marginRight':filmstrip_margin+'px',
                                'marginBottom':opts.frame_gap+'px'
                            }); break;
                case 'right': j_frames.css({
                                'marginLeft':filmstrip_margin+'px',
                                'marginBottom':opts.frame_gap+'px'
                            }); break;
            }
            $('.img_wrap',j_frames).each(function(i){                                  
                $(this).css({
                    'height':Math.min(opts.frame_height,img_h[i%item_count]*frame_img_scale[i%item_count])+'px',
                    'width':Math.min(opts.frame_width,img_w[i%item_count]*frame_img_scale[i%item_count])+'px',
                    'position':'relative',
                    'top':(opts.show_captions && opts.filmstrip_position=='top'?frame_caption_size:0)+Math.max(0,(opts.frame_height-(frame_img_scale[i%item_count]*img_h[i%item_count]))/2)+'px',
                    'left':Math.max(0,(opts.frame_width-(frame_img_scale[i%item_count]*img_w[i%item_count]))/2)+'px',
                    'overflow':'hidden'
                });
            });
            $('img',j_frames).each(function(i){
                $(this).css({
                    'opacity':opts.frame_opacity,
                    'height':img_h[i%item_count]*frame_img_scale[i%item_count]+'px',
                    'width':img_w[i%item_count]*frame_img_scale[i%item_count]+'px',
                    'position':'relative',
                    'top':Math.min(0,(opts.frame_height-(frame_img_scale[i%item_count]*img_h[i%item_count]))/2)+'px',
                    'left':Math.min(0,(opts.frame_width-(frame_img_scale[i%item_count]*img_w[i%item_count]))/2)+'px'
    
                }).mouseover(function(){
                    $(this).stop().animate({'opacity':1.0},300);
                }).mouseout(function(){
                    //Don't fade out current frame on mouseout
                    if(!$(this).parent().parent().hasClass('current')) $(this).stop().animate({'opacity':opts.frame_opacity},300);
                });
            });
            $('.strip_wrapper',j_gallery).css({
                'position':'absolute',
                'overflow':'hidden'
            });
            if(filmstrip_orientation=='horizontal') {
                $('.strip_wrapper',j_gallery).css({
                    'top':(opts.filmstrip_position=='top'?Math.max(gallery_padding,filmstrip_margin)+'px':opts.panel_height+gallery_padding+'px'),
                    'left':((gallery_width-wrapper_width)/2)+gallery_padding+'px',
                    'width':wrapper_width+'px',
                    'height':strip_height+'px'
                });
            } else {
                $('.strip_wrapper',j_gallery).css({
                    'left':(opts.filmstrip_position=='left'?Math.max(gallery_padding,filmstrip_margin)+'px':opts.panel_width+gallery_padding+'px'),
                    'top':Math.max(gallery_padding,opts.frame_gap)+'px',
                    'width':strip_width+'px',
                    'height':wrapper_height+'px'
                });
            }
            $('.caption',j_gallery).css({
                'position':'absolute',
                'top':(opts.filmstrip_position=='bottom'?f_frame_height:0)+'px',
                'left':'0',
                'margin':'0',
                'width':f_frame_width+'px',
                'padding':'0',
                'height':frame_caption_size+'px',
                'overflow':'hidden',
                'lineHeight':frame_caption_size+'px'
            });
            var pointer = $('<div></div>');
            pointer.addClass('pointer').appendTo(j_gallery).css({
                 'position':'absolute',
                 'zIndex':'1000',
                 'width':'0px',
                 'fontSize':'0px',
                 'lineHeight':'0%',
                 'borderTopWidth':pointer_height+'px',
                 'borderRightWidth':(pointer_width/2)+'px',
                 'borderBottomWidth':pointer_height+'px',
                 'borderLeftWidth':(pointer_width/2)+'px',
                 'borderStyle':'solid'
            });
            
            //For IE6, use predefined color string in place of transparent (see stylesheet)
            var transColor = $.browser.msie && $.browser.version.substr(0,1)=='6' ? 'pink' : 'transparent'
            
            if(!opts.show_panels) { pointer.css('borderColor',transColor); }
        
                switch(opts.filmstrip_position) {
                    case 'top': pointer.css({
                                    'bottom':(opts.panel_height-(pointer_height*2)+gallery_padding+filmstrip_margin)+'px',
                                     'left':((gallery_width-wrapper_width)/2)+(slide_method=='strip'?0:((f_frame_width+opts.frame_gap)*iterator))+((f_frame_width/2)-(pointer_width/2))+gallery_padding+'px',
                                    'borderBottomColor':transColor,
                                    'borderRightColor':transColor,
                                    'borderLeftColor':transColor
                                }); break;
                    case 'bottom': pointer.css({
                                        'top':(opts.panel_height-(pointer_height*2)+gallery_padding+filmstrip_margin)+'px',
                                         'left':((gallery_width-wrapper_width)/2)+(slide_method=='strip'?0:((f_frame_width+opts.frame_gap)*iterator))+((f_frame_width/2)-(pointer_width/2))+gallery_padding+'px',
                                        'borderTopColor':transColor,
                                        'borderRightColor':transColor,
                                        'borderLeftColor':transColor
                                    }); break;
                    case 'left': pointer.css({
                                    'right':(opts.panel_width-pointer_width+gallery_padding+filmstrip_margin)+'px',
                                     'top':(f_frame_height/2)-(pointer_height)+(slide_method=='strip'?0:((f_frame_height+opts.frame_gap)*iterator))+gallery_padding+'px',
                                    'borderBottomColor':transColor,
                                    'borderRightColor':transColor,
                                    'borderTopColor':transColor
                                }); break;
                    case 'right': pointer.css({
                                    'left':(opts.panel_width-pointer_width+gallery_padding+filmstrip_margin)+'px',
                                     'top':(f_frame_height/2)-(pointer_height)+(slide_method=='strip'?0:((f_frame_height+opts.frame_gap)*iterator))+gallery_padding+'px',
                                    'borderBottomColor':transColor,
                                    'borderLeftColor':transColor,
                                    'borderTopColor':transColor
                                }); break;
                }
        
            j_pointer = $('.pointer',j_gallery);
            
            //Add navigation buttons
            var navNext = $('<img />');
            navNext.addClass('nav-next').attr('src','/gfx/scrollRight.png').appendTo(j_gallery).css({ //Peter N
            //navNext.addClass('nav-next').attr('src',theme_path+opts.nav_theme+'/next.gif').appendTo(j_gallery).css({
                'position':'absolute',
                'cursor':'pointer'
            }).click(showNextItem);
            var navPrev = $('<img />');
            navPrev.addClass('nav-prev').attr('src','/gfx/scrollLeft.png').appendTo(j_gallery).css({
            //navPrev.addClass('nav-prev').attr('src',theme_path+opts.nav_theme+'/prev.gif').appendTo(j_gallery).css({
                'position':'absolute',
                'cursor':'pointer'
            }).click(showPrevItem);
            if(filmstrip_orientation=='horizontal') {
                navNext.css({                     
                    'top':(opts.filmstrip_position=='top'?Math.max(gallery_padding,filmstrip_margin):opts.panel_height+filmstrip_margin+gallery_padding)+((f_frame_height-22)/2)+'px',
                    'right':((gallery_width+(gallery_padding*2))/2)-(wrapper_width/2)-opts.frame_gap-22+'px'
                });
                navPrev.css({
                    'top':(opts.filmstrip_position=='top'?Math.max(gallery_padding,filmstrip_margin):opts.panel_height+filmstrip_margin+gallery_padding)+((f_frame_height-22)/2)+'px',
                    'left':((gallery_width+(gallery_padding*2))/2)-(wrapper_width/2)-opts.frame_gap-22+'px'
                 });
            } else {
                navNext.css({                     
                    'left':(opts.filmstrip_position=='left'?Math.max(gallery_padding,filmstrip_margin):opts.panel_width+filmstrip_margin+gallery_padding)+((f_frame_width-22)/2)+13+'px',
                    'top':wrapper_height+(Math.max(gallery_padding,opts.frame_gap)*2)+'px'
                });
                navPrev.css({
                    'left':(opts.filmstrip_position=='left'?Math.max(gallery_padding,filmstrip_margin):opts.panel_width+filmstrip_margin+gallery_padding)+((f_frame_width-22)/2)-13+'px',
                    'top':wrapper_height+(Math.max(gallery_padding,opts.frame_gap)*2)+'px'
                });
            }
        };
        
    //Check mouse to see if it is within the borders of the panel
    //More reliable than 'mouseover' event when elements overlay the panel
        function mouseIsOverGallery(x,y) {        
            var pos = getPos(j_gallery[0]);
            var top = pos.top;
            var left = pos.left;
            return x > left && x < left+gallery_width+(filmstrip_orientation=='horizontal'?(gallery_padding*2):gallery_padding+Math.max(gallery_padding,filmstrip_margin)) && y > top && y < top+gallery_height+(filmstrip_orientation=='vertical'?(gallery_padding*2):gallery_padding+Math.max(gallery_padding,filmstrip_margin));                
        };
        
        function getInt(i) {
            i = parseInt(i,10);
            if(isNaN(i)) { i = 0; }
            return i;    
        }
                    
        function buildGallery() {
          
            var gallery_images = opts.show_filmstrip?$('img',j_frames):$('img',j_panels);
            gallery_images.each(function(i){
                img_h[i] = this.height;
                img_w[i] = this.width;
                if(opts.frame_scale=='nocrop') {
                    frame_img_scale[i] = Math.min(opts.frame_height/img_h[i],opts.frame_width/img_w[i]);
                } else {
                    frame_img_scale[i] = Math.max(opts.frame_height/img_h[i],opts.frame_width/img_w[i]);
                    
                }
                
                if(opts.panel_scale=='nocrop') {
                    panel_img_scale[i] = Math.min(opts.panel_height/img_h[i],opts.panel_width/img_w[i]);
                } else {
                    panel_img_scale[i] = Math.max(opts.panel_height/img_h[i],opts.panel_width/img_w[i]);
                }
            });
    
    /************************************************/
    /*    Apply CSS Styles                            */
    /************************************************/
            j_gallery.css({
                'position':'relative',
                'width':gallery_width+(filmstrip_orientation=='horizontal'?(gallery_padding*2):gallery_padding+Math.max(gallery_padding,filmstrip_margin))+'px',
                'height':gallery_height+(filmstrip_orientation=='vertical'?(gallery_padding*2):gallery_padding+Math.max(gallery_padding,filmstrip_margin))+'px'
            });
    
    /************************************************/
    /*    Build filmstrip and/or panels                */
    /************************************************/
            if(opts.show_filmstrip) {
                buildFilmstrip();
                enableFrameClicking();
            }
            if(opts.show_panels) {
                buildPanels();
            }

    /************************************************/
    /*    Add events to various elements                */
    /************************************************/
            if(opts.pause_on_hover || (opts.show_panels && !opts.show_filmstrip)) {
                $().mousemove(function(e){                            
                    if(mouseIsOverGallery(e.pageX,e.pageY)) {
                        if(opts.pause_on_hover) {
                            if(!paused) {
                                $(document).oneTime(500,"animation_pause",function(){
                                    $(document).stopTime("transition");
                                    paused=true;
                                });
                            }
                        }
                        if(opts.show_panels && !opts.show_filmstrip && !panel_nav_displayed) {
                            $('.nav-next-overlay').fadeIn('fast');
                            $('.nav-prev-overlay').fadeIn('fast');
                            $('.nav-next',j_gallery).fadeIn('fast');
                            $('.nav-prev',j_gallery).fadeIn('fast');
                            panel_nav_displayed = true;
                        }
                    } else {
                        if(opts.pause_on_hover) {
                            $(document).stopTime("animation_pause");
                            if(paused) {
                                $(document).everyTime(opts.transition_interval,"transition",function(){
                                    showNextItem();
                                });
                                paused = false;
                            }
                        }
                        if(opts.show_panels && !opts.show_filmstrip && panel_nav_displayed) {
                            $('.nav-next-overlay').fadeOut('fast');
                            $('.nav-prev-overlay').fadeOut('fast');
                            $('.nav-next',j_gallery).fadeOut('fast');
                            $('.nav-prev',j_gallery).fadeOut('fast');
                            panel_nav_displayed = false;
                        }
                    }
                });
            }
    
    
    /****************************************************************/
    /*    Initiate Automated Animation                                */
    /****************************************************************/
            
            //Hide loading box
            j_filmstrip.css('visibility','visible');
            j_gallery.css('visibility','visible');
            $('.loader',j_gallery).fadeOut('1000',function(){
                //Show the 'first' panel
                showItem(iterator);
                //If we have more than one item, begin automated transitions
                if(item_count > 1) {
                    $(document).everyTime(opts.transition_interval,"transition",function(){
                        showNextItem();
                    });
                }    
            });    
        }
        
/************************************************/
/*    Main Plugin Code                            */
/************************************************/
        return this.each(function() {
            //Hide <ul>
            $(this).css('visibility','hidden');
            
            //Wrap <ul> in <div> and transfer ID to container <div>
            //Assign filmstrip class to <ul>
            $(this).wrap("<div></div>");
            j_gallery = $(this).parent();
            j_gallery.css('visibility','hidden').attr('id',$(this).attr('id')).addClass('preview_set');
            $(this).removeAttr('id').addClass('filmstrip');
            
            $(document).stopTime("transition");
            $(document).stopTime("animation_pause");
            
            id = j_gallery.attr('id');
            
            //If there is no defined panel content, we will scale panel images
            scale_panel_images = $('.panel-content',j_gallery).length==0;
            
            //Define dimensions of pointer <div>
            pointer_height = opts.pointer_size;
            pointer_width = opts.pointer_size*2;
            
            //Determine filmstrip orientation (vertical or horizontal)
            //Do not show captions on vertical filmstrips
            filmstrip_orientation = (opts.filmstrip_position=='top'||opts.filmstrip_position=='bottom'?'horizontal':'vertical');
            if(filmstrip_orientation=='vertical') opts.show_captions = false;
            
            //Determine path between current page and plugin images
            //Scan script tags and look for path to GalleryView plugin
            $('script').each(function(i){
                var s = $(this);
                if(s.attr('src') && s.attr('src').match(/jquery\.galleryview/)){
                    loader_path = s.attr('src').split('jquery.galleryview')[0];
                    theme_path = s.attr('src').split('jquery.galleryview')[0]+'themes/';    
                }
            });
            
            j_filmstrip = $('.filmstrip',j_gallery);
            j_frames = $('li',j_filmstrip);
            j_frames.addClass('frame');
            
            //If the user wants panels, generate them using the filmstrip images
            if(opts.show_panels) {
                for(i=j_frames.length-1;i>=0;i--) {
                    if(j_frames.eq(i).find('.panel-content').length>0) {
                        j_frames.eq(i).find('.panel-content').remove().prependTo(j_gallery).addClass('panel');
                    } else {
                        p = $('<div>');
                        p.addClass('panel');
                        im = $('<img />');
                        im.attr('src',j_frames.eq(i).find('img').eq(0).attr('src')).appendTo(p);
                        p.prependTo(j_gallery);
                        j_frames.eq(i).find('.panel-overlay').remove().appendTo(p);
                    }
                }
            } else { 
                $('.panel-overlay',j_frames).remove(); 
                $('.panel-content',j_frames).remove();
            }
            
            //If the user doesn't want a filmstrip, delete it
            if(!opts.show_filmstrip) { j_filmstrip.remove(); }
            else {
                //Wrap the frame images (and links, if applicable) in container divs
                //These divs will handle cropping and zooming of the images
                j_frames.each(function(i){
                    if($(this).find('a').length>0) {
                        $(this).find('a').wrap('<div class="img_wrap"></div>');
                    } else {
                        $(this).find('img').wrap('<div class="img_wrap"></div>');    
                    }
                });
                j_frame_img_wrappers = $('.img_wrap',j_frames);
            }
            
            j_panels = $('.panel',j_gallery);
            
            if(!opts.show_panels) {
                opts.panel_height = 0;
                opts.panel_width = 0;
            }
            
            
            //Determine final frame dimensions, accounting for user-added padding and border
            f_frame_width = opts.frame_width+extraWidth(j_frame_img_wrappers);
            f_frame_height = opts.frame_height+extraHeight(j_frame_img_wrappers);
            
            //Number of frames in filmstrip
            item_count = opts.show_panels?j_panels.length:j_frames.length;
            
            //Number of frames that can display within the gallery block
            //64 = width of block for navigation button * 2 + 20
            if(filmstrip_orientation=='horizontal') {
                strip_size = opts.show_panels?Math.floor((opts.panel_width-((opts.frame_gap+22)*2))/(f_frame_width+opts.frame_gap)):Math.min(item_count,opts.filmstrip_size); 
            } else {
                strip_size = opts.show_panels?Math.floor((opts.panel_height-(opts.frame_gap+22))/(f_frame_height+opts.frame_gap)):Math.min(item_count,opts.filmstrip_size);
            }
            
            /************************************************/
            /*    Determine transition method for filmstrip    */
            /************************************************/
                    //If more items than strip size, slide filmstrip
                    //Otherwise, slide pointer
                    if(strip_size >= item_count) {
                        slide_method = 'pointer';
                        strip_size = item_count;
                    }
                    else {slide_method = 'strip';}
                    
                    iterator = (strip_size<item_count?item_count:0)+opts.start_frame-1;
            
            /************************************************/
            /*    Determine dimensions of various elements    */
            /************************************************/
                    filmstrip_margin = (opts.show_panels?getInt(j_filmstrip.css('marginTop')):0);
                    j_filmstrip.css('margin','0px');
                    
                    if(filmstrip_orientation=='horizontal') {
                        //Width of gallery block
                        gallery_width = opts.show_panels?opts.panel_width:(strip_size*(f_frame_width+opts.frame_gap))+44+opts.frame_gap;
                        
                        //Height of gallery block = screen + filmstrip + captions (optional)
                        gallery_height = (opts.show_panels?opts.panel_height:0)+(opts.show_filmstrip?f_frame_height+filmstrip_margin+(opts.show_captions?frame_caption_size:0):0);
                    } else {
                        //Width of gallery block
                        gallery_height = opts.show_panels?opts.panel_height:(strip_size*(f_frame_height+opts.frame_gap))+22;
                        
                        //Height of gallery block = screen + filmstrip + captions (optional)
                        gallery_width = (opts.show_panels?opts.panel_width:0)+(opts.show_filmstrip?f_frame_width+filmstrip_margin:0);
                    }
                    
                    
                    
                    //Width of filmstrip
                    if(filmstrip_orientation=='horizontal') {
                        if(slide_method == 'pointer') {strip_width = (f_frame_width*item_count)+(opts.frame_gap*(item_count));}
                        else {strip_width = (f_frame_width*item_count*3)+(opts.frame_gap*(item_count*3));}
                    } else {
                        strip_width = (f_frame_width+filmstrip_margin);
                    }
                    
                    if(filmstrip_orientation=='horizontal') {
                        strip_height = (f_frame_height+filmstrip_margin+(opts.show_captions?frame_caption_size:0));    
                    } else {
                        if(slide_method == 'pointer') {strip_height = (f_frame_height*item_count+opts.frame_gap*(item_count));}
                        else {strip_height = (f_frame_height*item_count*3)+(opts.frame_gap*(item_count*3));}
                    }
                    
                    //Width of filmstrip wrapper (to hide overflow)
                    wrapper_width = ((strip_size*f_frame_width)+((strip_size-1)*opts.frame_gap));
                    wrapper_height = ((strip_size*f_frame_height)+((strip_size-1)*opts.frame_gap));

                    
                    gallery_padding = getInt(j_gallery.css('paddingTop'));
                    j_gallery.css('padding','0px');
            /********************************************************/
            /*    PLACE LOADING BOX OVER GALLERY UNTIL IMAGES LOAD    */
            /********************************************************/
                    galleryPos = getPos(j_gallery[0]);
                    $('<div>').addClass('loader').css({
                        'position':'absolute',
                        'zIndex':'32666',
                        'opacity':1,
                        'top':'0px',
                        'left':'0px',
                        'width':gallery_width+(filmstrip_orientation=='horizontal'?(gallery_padding*2):gallery_padding+Math.max(gallery_padding,filmstrip_margin))+'px',
                        'height':gallery_height+(filmstrip_orientation=='vertical'?(gallery_padding*2):gallery_padding+Math.max(gallery_padding,filmstrip_margin))+'px'
                    }).appendTo(j_gallery);
                    
            
            /*if(!window_loaded) {
                $(window).load(function(){
                    window_loaded = true;
                    buildGallery();
                });
            } else {
              */  
                buildGallery();
            //}
            
                    
        });
    };
    
    $.fn.galleryView.defaults = {
        
        show_panels: true,
        show_filmstrip: true,
        
        panel_width: 600,
        panel_height: 400,
        frame_width: 60,
        frame_height: 40,
        
        start_frame: 1,
        filmstrip_size: 3,
        transition_speed: 800,
        transition_interval: 4000,
        
        overlay_opacity: 0.7,
        frame_opacity: 0.3,
        
        pointer_size: 8,
        
        nav_theme: 'dark',
        easing: 'swing',
        
        filmstrip_position: 'bottom',
        overlay_position: 'bottom',
        
        panel_scale: 'nocrop',
        frame_scale: 'crop',
        
        frame_gap: 5,
        
        show_captions: false,
        fade_panels: true,
        pause_on_hover: false
    };     
})(jQuery);
/*
 * jQuery PHP Plugin
 * version: 0.8.3 (21/11/2008)
 * author:  Anton Shevchuk (http://anton.shevchuk.name)
 * @requires jQuery v1.2.1 or later
 *
 * Examples and documentation at: http://jquery.hohli.com/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id$
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('5={15:7(){v U},10:7(c,d){16(l i=0;i<c[\'q\'].p;i++){l e=8(c[\'q\'][i][\'s\']);l f=c[\'q\'][i][\'m\'];l g=c[\'q\'][i][\'a\'];16(l j=0;j<f.p;j++){1w{l h=f[j];l k=g[j];W(h&&h!=\'\'&&h!=\'1n\'){1q(U){o(h==\'2i\'||h==\'2k\'||h==\'2o\'):e=e[h](r[k[0]]);9;o((h==\'2L\'||h==\'2M\')&&k.p==3):e=e[h](k[0],k[1],r[k[2]]);9;o((h==\'2b\'||h==\'17\')&&k.p==2):e=e[h](r[k[0]],r[k[1]]);9;o(h==\'24\'&&k.p==1):W(r[k[0]]&&r[k[0]]!=\'\'&&r[k[0]]!=\'1n\'){e=e[h](r[k[0]])}26{e=e[h](k[0])}9;o((h==\'1O\'||h==\'2m\'||h==\'2s\'||h==\'2I\'||h==\'19\'||h==\'32\'||h==\'1J\')&&k.p==2):e=e[h](k[0],r[k[1]]);9;o((h==\'2X\'||h==\'2e\'||h==\'M\'||h==\'2T\'||h==\'6\'||h==\'30\'||h==\'3a\'||h==\'2D\'||h==\'2n\'||h==\'2Q\'||h==\'29\'||h==\'2S\'||h==\'2U\'||h==\'2V\'||h==\'2r\'||h==\'31\'||h==\'35\'||h==\'1X\'||h==\'22\'||h==\'2a\')&&k.p==1):e=e[h](r[k[0]]);9;o(h==\'2c\'&&k.p==3):e=e[h](k[0],k[1],r[k[2]]);9;o(h==\'2g\'&&k.p==4):e=e[h](k[0],k[1],k[2],r[k[3]]);9;o(k.p==0):e=e[h]();9;o(k.p==1):e=e[h](k[0]);9;o(k.p==2):e=e[h](k[0],k[1]);9;o(k.p==3):e=e[h](k[0],k[1],k[2]);9;o(k.p==4):e=e[h](k[0],k[1],k[2],k[3]);9;1G:e=e[h](k);9}}}V(6){S(\'1x: 8("\'+c[\'q\'][i][\'s\']+\'").\'+h+\'("\'+k+\'")\\n\'+\' 12 1e: \'+6.1f+\'\\n\'+\' 1k G: \'+6.1C+\'\\n\'+\' 6:   \'+6.14)}}}8.1W(c[\'a\'],7(a,b){16(l i=0;i<b.p;i++){1w{5[a](b[i])}V(6){S(\'1x: \'+a+\'(\'+b[i]+\')\\n\'+\' 12 1e: \'+6.1f+\'\\n\'+\' 1k G: \'+6.1C+\'\\n\'+\' 6:   \'+6.14)}}})},6:7(a,b,c){l d=c?c:18;8(\'#5-6\').1p();l e="<1t 1R=\'H/D\'>"+"#5-6{ y:2y; F:1a; 1c:I; 13:I; T:J P #L; }"+"#5-6 .5-1m{ y:1o; x:1s; F:1u; G-x:1s; w-u:#2Z; u:#1d; 1A-2d:2z; 1A-1U:1V;Y-1E:I; }"+"#5-6 .5-C { y:A;  x:A; F:1a; 1c:K; 13:28; G-x:A; H-1I:1K; 1T:1M; T:J P #L; w-u:#E; u:#1Q; }"+"#5-6 .5-Q{ y:A;  x:A; F:1a; 1c:K; 13:K;  G-x:A; H-1I:1K; 1T:1M; T:J P #L; w-u:#E; u:#1Q; }"+"#5-6 .5-1S { y:1o; F:1u; w-u:#E; T-2q:J P #L;Y-1E:I;}"+"#5-6 .5-N{ 2u:2w;}"+"#5-6 11{ y:2A;x:2C;2E:2G;Y:K;}"+"</1t>";l f="<t 2K=\'5-6\'>"+"<t z=\'5-1m\'>2N 12 2P 2R"+"<t z=\'5-C\'>&1z;</t>"+"<t z=\'5-Q\'>X</t>"+"</t>"+"<t z=\'5-1S\'>";f+="<b>2W 2Y</b>: ";1q(a.1g){o 0:B="34 36";9;o 1:B="38";9;o 2:B="1B 3c";9;o 3:B="3d";9;o 4:B="2f";9;1G:v"2B 25"}f+=B+" ("+a.1g+")";f+="<Z/>\\n";W(d!=18){f+="2h 2F V: "+c.1Y();f+="<Z/>\\n"}f+="<b>2H 1D</b>: "+a.1D+" - "+a.2J;f+="<Z/>\\n";f+="<b>27 H</b> (<1j><a 2l=\'#\' z=\'5-1F\'>1O C 21 &1z;</a></1j>):";f+="</t>\\n";f+="<t z=\'5-N\'><11>"+a.2O+"</11></t>";f+="</t>";8(1r.1H).1h(e);8(1r.1H).1h(f);8(\'#5-6 .5-C\').17(7(){8(O).D(\'w-u\',\'#1d\')},7(){8(O).D(\'w-u\',\'#E\')});8(\'#5-6 .5-C\').M(7(){8(\'#5-6 .5-N\').19()});8(\'#5-6 .5-1F\').M(7(){8(\'#5-6 .5-N\').19();v 18});8(\'#5-6 .5-Q\').M(7(){8(\'#5-6\').1J(\'2p\',7(){8(\'#5-6\').1p()})});8(\'#5-6 .5-Q\').17(7(){8(O).D(\'w-u\',\'#1d\')},7(){8(O).D(\'w-u\',\'#E\')})},1b:7(a,b){v U},1Z:7(a){l b=a.1L||"";l c=a.1l||"R";l d=a.1N||{};5.1v[c](b,d)},2t:7(a){l b=a.1L||"";l c=a.1l||"R";l d=a.1N||{};5.1P[c](b,d)},23:7(a){l b=a.33||\'\';2v(b)},1v:{R:7(a,b){S("1i 1y 14: "+a)}},1P:{R:7(a,b){S("1i 1y 6: "+a)}}};8.37({5:7(d,e){8.2x({39:d,1R:"20",1B:e,3b:"2j",15:7(){v 5.15()},10:7(a,b){v 5.10(a,b)},6:7(a,b,c){v 5.6(a,b,c)},1b:7(a,b){v 5.1b(a,b)}})}});',62,200,'|||||php|error|function|jQuery|break||||||||||||var|||case|length||window||div|color|return|background|height|width|class|20px|readyStDesc|more|css|fee|position|line|text|4px|1px|2px|f00|click|content|this|solid|close|defaultCallBack|alert|border|true|catch|if||padding|br|success|textarea|in|right|message|beforeSend|for|hover|false|slideToggle|absolute|complete|top|fff|file|fileName|readyState|append|Server|small|on|callback|title|undefined|636px|remove|switch|document|26px|style|relative|messages|try|onAction|response|raquo|font|data|lineNumber|status|left|more2|default|body|align|fadeOut|center|msg|pointer|params|show|errors|333|type|desc|cursor|size|12px|each|scroll|toString|addMessage|POST|information|select|evalScript|filter|state|else|Response|24px|unload|submit|toggle|fadeTo|weight|change|finish|animate|exception|ready|json|map|href|hide|keyup|queue|fast|bottom|mouseover|slideDown|addError|display|eval|none|ajax|640px|bold|634px|uncknown|400px|keypress|overflow|was|auto|HTTP|slideUp|statusText|id|bind|one|Error|responseText|AJAX|load|request|mousedown|dblclick|mousemove|mouseout|XMLHttpRequest|blur|exchange|f66|focus|mouseup|fadeIn|foo|not|resize|initialize|extend|open|url|keydown|dataType|transfer|loading'.split('|'),0,{}));

/*
 * jquery.tools 1.1.0 - The missing UI library for the Web
 * 
 * [tools.overlay-1.1.0, tools.overlay.apple-1.0.0, tools.expose-1.0.4]
 * 
 * Copyright (c) 2009 Tero Piirainen
 * http://flowplayer.org/tools/
 *
 * Dual licensed under MIT and GPL 2+ licenses
 * http://www.opensource.org/licenses
 * 
 * -----
 * 
 * File generated: Thu Sep 03 21:57:48 GMT+00:00 2009
 */
(function(c){c.tools=c.tools||{};c.tools.overlay={version:"1.1.0",addEffect:function(e,f,g){b[e]=[f,g]},conf:{top:"10%",left:"center",absolute:false,speed:"normal",closeSpeed:"fast",effect:"default",close:null,oneInstance:true,closeOnClick:true,closeOnEsc:true,api:false,expose:null,target:null}};var b={};c.tools.overlay.addEffect("default",function(e){this.getOverlay().fadeIn(this.getConf().speed,e)},function(e){this.getOverlay().fadeOut(this.getConf().closeSpeed,e)});var d=[];function a(i,f){var p=this,o=c(window),l,k,j,g=f.expose&&c.tools.expose.version;var h=f.target||i.attr("rel");k=h?c(h):null||i;if(i){i.click(function(q){p.load();return q.preventDefault()})}function n(e,q){c(p).bind(e,function(s,r){if(q&&q.call(this)===false&&r){r.proceed=false}});return p}c.each(f,function(e,q){if(c.isFunction(q)){n(e,q)}});c.extend(p,{load:function(){if(p.isOpened()){return p}if(f.oneInstance){c.each(d,function(){this.close()})}var t={proceed:true};c(p).trigger("onBeforeLoad",t);if(!t.proceed){return p}if(g){k.expose().load()}var s=f.top;if(typeof s=="string"){s=parseInt(s,10)/100*o.height()}var r=f.left;var e=k.outerWidth({margin:true});var q=k.outerHeight({margin:true});if(s=="center"){s=Math.max((o.height()-q)/2,0)}if(r=="center"){r=Math.max((o.width()-e)/2,0)}if(!f.absolute){s+=o.scrollTop();r+=o.scrollLeft()}k.css({top:s,left:r,position:"absolute"});b[f.effect][0].call(p,function(){c(p).trigger("onLoad");j=true});if(f.closeOnClick){c(document).bind("click.overlay",function(u){if(!p.isOpened()){return}var v=c(u.target);if(v.parents(k).length>1){return}c.each(d,function(){this.close()})})}if(f.closeOnEsc){c(document).unbind("keydown.overlay").bind("keydown.overlay",function(u){if(u.keyCode==27){c.each(d,function(){this.close()})}})}return p},close:function(){if(!p.isOpened()){return p}var q={proceed:true};c(p).trigger("onBeforeClose",q);if(!q.proceed){return p}b[f.effect][1].call(p,function(){j=false;c(p).trigger("onClose")});var e=true;c.each(d,function(){if(this.isOpened()){e=false}});if(e){c(document).unbind("click.overlay").unbind("keydown.overlay")}return p},getContent:function(){return k},getOverlay:function(){return k},getTrigger:function(){return i},getClosers:function(){return l},isOpened:function(){return j},getConf:function(){return f},onBeforeLoad:function(e){return n("onBeforeLoad",e)},onLoad:function(e){return n("onLoad",e)},onBeforeClose:function(e){return n("onBeforeClose",e)},onClose:function(e){return n("onClose",e)}});if(g){if(typeof f.expose=="string"){f.expose={color:f.expose}}c.extend(f.expose,{api:true,closeOnClick:f.closeOnClick,closeOnEsc:false});var m=k.expose(f.expose);m.onBeforeClose(function(){p.close()});p.onClose(function(){m.close()})}l=k.find(f.close||".close");if(!l.length&&!f.close){l=c('<div class="close"></div>');k.prepend(l)}l.click(function(){p.close()})}c.fn.overlay=function(e){var f=this.eq(typeof e=="number"?e:0).data("overlay");if(f){return f}if(c.isFunction(e)){e={onBeforeLoad:e}}var g=c.extend({},c.tools.overlay.conf);c.extend(true,g,e);this.each(function(){f=new a(c(this),g);d.push(f);c(this).data("overlay",f)});return g.api?f:this}})(jQuery);
(function(d){var b=d.tools.overlay;b.effects=b.effects||{};b.effects.apple={version:"1.0.0"};d.extend(b.conf,{start:{absolute:true,top:null,left:null},fadeInSpeed:"fast",zIndex:5001});function c(f){var g=f.offset();return[g.top+f.height()/2,g.left+f.width()/2]}var e=function(n){var k=this.getOverlay(),f=this.getConf(),i=this.getTrigger(),q=this,r=k.outerWidth({margin:true}),m=k.data("img");if(!m){var l=k.css("backgroundImage");if(!l){throw"background-image CSS property not set for overlay"}l=l.substring(l.indexOf("(")+1,l.indexOf(")")).replace(/\"/g,"");k.css("backgroundImage","none");m=d('<img src="'+l+'"/>');m.css({border:0,position:"absolute",display:"none"}).width(r);d("body").append(m);k.data("img",m)}var o=d(window),j=f.start.top||Math.round(o.height()/2),h=f.start.left||Math.round(o.width()/2);if(i){var g=c(i);j=g[0];h=g[1]}if(!f.start.absolute){j+=o.scrollTop();h+=o.scrollLeft()}m.css({top:j,left:h,width:0,zIndex:f.zIndex}).show();m.animate({top:k.css("top"),left:k.css("left"),width:r},f.speed,function(){q.getClosers().add(k).css("zIndex",f.zIndex+1).fadeIn(f.fadeInSpeed,function(){if(!d(this).index(k)){n.call()}})})};var a=function(f){var h=this.getOverlay(),i=this.getConf(),g=this.getTrigger(),l=i.start.top,k=i.start.left;h.hide();if(g){var j=c(g);l=j[0];k=j[1]}h.data("img").animate({top:l,left:k,width:0},i.closeSpeed,f)};b.addEffect("apple",e,a)})(jQuery);
(function(b){b.tools=b.tools||{};b.tools.expose={version:"1.0.4",conf:{maskId:null,loadSpeed:"slow",closeSpeed:"fast",closeOnClick:true,closeOnEsc:true,zIndex:5000,opacity:0.8,color:"#456",api:false}};function a(){if(b.browser.msie){var f=b(document).height(),e=b(window).height();return[window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,f-e<20?e:f]}return[b(window).width(),b(document).height()]}function c(g,h){var e=this,d=null,f=false,i=0;function j(k,l){b(e).bind(k,function(n,m){if(l&&l.call(this)===false&&m){m.proceed=false}});return e}b.each(h,function(k,l){if(b.isFunction(l)){j(k,l)}});b(window).resize(function(){e.fit()});b.extend(this,{getMask:function(){return d},getExposed:function(){return g},getConf:function(){return h},isLoaded:function(){return f},load:function(){if(f){return e}i=g.eq(0).css("zIndex");if(h.maskId){d=b("#"+h.maskId)}if(!d||!d.length){var l=a();d=b("<div/>").css({position:"absolute",top:0,left:0,width:l[0],height:l[1],display:"none",opacity:0,zIndex:h.zIndex});if(h.maskId){d.attr("id",h.maskId)}b("body").append(d);var k=d.css("backgroundColor");if(!k||k=="transparent"||k=="rgba(0, 0, 0, 0)"){d.css("backgroundColor",h.color)}if(h.closeOnEsc){b(document).bind("keydown.unexpose",function(o){if(o.keyCode==27){e.close()}})}if(h.closeOnClick){d.bind("click.unexpose",function(){e.close()})}}var n={proceed:true};b(e).trigger("onBeforeLoad",n);if(!n.proceed){return e}b.each(g,function(){var o=b(this);if(!/relative|absolute|fixed/i.test(o.css("position"))){o.css("position","relative")}});g.css({zIndex:Math.max(h.zIndex+1,i=="auto"?0:i)});var m=d.height();if(!this.isLoaded()){d.css({opacity:0,display:"block"}).fadeTo(h.loadSpeed,h.opacity,function(){if(d.height()!=m){d.css("height",m)}b(e).trigger("onLoad")})}f=true;return e},close:function(){if(!f){return e}var k={proceed:true};b(e).trigger("onBeforeClose",k);if(k.proceed===false){return e}d.fadeOut(h.closeSpeed,function(){b(e).trigger("onClose");g.css({zIndex:b.browser.msie?i:null})});f=false;return e},onBeforeLoad:function(k){return j("onBeforeLoad",k)},onLoad:function(k){return j("onLoad",k)},onBeforeClose:function(k){return j("onBeforeClose",k)},onClose:function(k){return j("onClose",k)},fit:function(){if(d){var k=a();d.css({width:k[0],height:k[1]})}}})}b.fn.expose=function(d){var e=this.eq(typeof d=="number"?d:0).data("expose");if(e){return e}if(typeof d=="string"){d={color:d}}var f=b.extend({},b.tools.expose.conf);b.extend(f,d);this.each(function(){e=new c(b(this),f);b(this).data("expose",e)});return f.api?e:this}})(jQuery);
    
/*
 * jQuery Autocomplete plugin 1.1
 *
 * Copyright (c) 2009 JÃ¶rn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $
 */

;(function($) {
	
$.fn.extend({
	autocomplete: function(urlOrData, options) {
		var isUrl = typeof urlOrData == "string";
		options = $.extend({}, $.Autocompleter.defaults, {
			url: isUrl ? urlOrData : null,
			data: isUrl ? null : urlOrData,
			delay: isUrl ? $.Autocompleter.defaults.delay : 10,
			max: options && !options.scroll ? 10 : 150
		}, options);
		
		// if highlight is set to false, replace it with a do-nothing function
		options.highlight = options.highlight || function(value) { return value; };
		
		// if the formatMatch option is not specified, then use formatItem for backwards compatibility
		options.formatMatch = options.formatMatch || options.formatItem;
		
		return this.each(function() {
			new $.Autocompleter(this, options);
		});
	},
	result: function(handler) {
		return this.bind("result", handler);
	},
	search: function(handler) {
		return this.trigger("search", [handler]);
	},
	flushCache: function() {
		return this.trigger("flushCache");
	},
	setOptions: function(options){
		return this.trigger("setOptions", [options]);
	},
	unautocomplete: function() {
		return this.trigger("unautocomplete");
	}
});

$.Autocompleter = function(input, options) {

	var KEY = {
		UP: 38,
		DOWN: 40,
		DEL: 46,
		TAB: 9,
		RETURN: 13,
		ESC: 27,
		COMMA: 188,
		PAGEUP: 33,
		PAGEDOWN: 34,
		BACKSPACE: 8
	};

	// Create $ object for input element
	var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);

	var timeout;
	var previousValue = "";
	var cache = $.Autocompleter.Cache(options);
	var hasFocus = 0;
	var lastKeyPressCode;
	var config = {
		mouseDownOnSelect: false
	};
	var select = $.Autocompleter.Select(options, input, selectCurrent, config);
	
	var blockSubmit;
	
	// prevent form submit in opera when selecting with return key
	$.browser.opera && $(input.form).bind("submit.autocomplete", function() {
		if (blockSubmit) {
			blockSubmit = false;
			return false;
		}
	});
	
	// only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
	$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
		// a keypress means the input has focus
		// avoids issue where input had focus before the autocomplete was applied
		hasFocus = 1;
		// track last key pressed
		lastKeyPressCode = event.keyCode;
		switch(event.keyCode) {
		
			case KEY.UP:
				event.preventDefault();
				if ( select.visible() ) {
					select.prev();
				} else {
					onChange(0, true);
				}
				break;
				
			case KEY.DOWN:
				event.preventDefault();
				if ( select.visible() ) {
					select.next();
				} else {
					onChange(0, true);
				}
				break;
				
			case KEY.PAGEUP:
				event.preventDefault();
				if ( select.visible() ) {
					select.pageUp();
				} else {
					onChange(0, true);
				}
				break;
				
			case KEY.PAGEDOWN:
				event.preventDefault();
				if ( select.visible() ) {
					select.pageDown();
				} else {
					onChange(0, true);
				}
				break;
			
			// matches also semicolon
			case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
			case KEY.TAB:
			case KEY.RETURN:
				if( selectCurrent() ) {
					// stop default to prevent a form submit, Opera needs special handling
					event.preventDefault();
					blockSubmit = true;
					return false;
				}
				break;
				
			case KEY.ESC:
				select.hide();
				break;
				
			default:
				clearTimeout(timeout);
				timeout = setTimeout(onChange, options.delay);
				break;
		}
	}).focus(function(){
		// track whether the field has focus, we shouldn't process any
		// results if the field no longer has focus
		hasFocus++;
	}).blur(function() {
		hasFocus = 0;
		if (!config.mouseDownOnSelect) {
			hideResults();
		}
	}).click(function() {
		// show select when clicking in a focused field
		if ( hasFocus++ > 1 && !select.visible() ) {
			onChange(0, true);
		}
	}).bind("search", function() {
		// TODO why not just specifying both arguments?
		var fn = (arguments.length > 1) ? arguments[1] : null;
		function findValueCallback(q, data) {
			var result;
			if( data && data.length ) {
				for (var i=0; i < data.length; i++) {
					if( data[i].result.toLowerCase() == q.toLowerCase() ) {
						result = data[i];
						break;
					}
				}
			}
			if( typeof fn == "function" ) fn(result);
			else $input.trigger("result", result && [result.data, result.value]);
		}
		$.each(trimWords($input.val()), function(i, value) {
			request(value, findValueCallback, findValueCallback);
		});
	}).bind("flushCache", function() {
		cache.flush();
	}).bind("setOptions", function() {
		$.extend(options, arguments[1]);
		// if we've updated the data, repopulate
		if ( "data" in arguments[1] )
			cache.populate();
	}).bind("unautocomplete", function() {
		select.unbind();
		$input.unbind();
		$(input.form).unbind(".autocomplete");
	});
	
	
	function selectCurrent() {
		var selected = select.selected();
		if( !selected )
			return false;
		
		var v = selected.result;
		previousValue = v;
		
		if ( options.multiple ) {
			var words = trimWords($input.val());
			if ( words.length > 1 ) {
				var seperator = options.multipleSeparator.length;
				var cursorAt = $(input).selection().start;
				var wordAt, progress = 0;
				$.each(words, function(i, word) {
					progress += word.length;
					if (cursorAt <= progress) {
						wordAt = i;
						return false;
					}
					progress += seperator;
				});
				words[wordAt] = v;
				// TODO this should set the cursor to the right position, but it gets overriden somewhere
				//$.Autocompleter.Selection(input, progress + seperator, progress + seperator);
				v = words.join( options.multipleSeparator );
			}
			v += options.multipleSeparator;
		}
		
		$input.val(v);
		hideResultsNow();
		$input.trigger("result", [selected.data, selected.value]);
		return true;
	}
	
	function onChange(crap, skipPrevCheck) {
		if( lastKeyPressCode == KEY.DEL ) {
			select.hide();
			return;
		}
		
		var currentValue = $input.val();
		
		if ( !skipPrevCheck && currentValue == previousValue )
			return;
		
		previousValue = currentValue;
		
		currentValue = lastWord(currentValue);
		if ( currentValue.length >= options.minChars) {
			$input.addClass(options.loadingClass);
			if (!options.matchCase)
				currentValue = currentValue.toLowerCase();
			request(currentValue, receiveData, hideResultsNow);
		} else {
			stopLoading();
			select.hide();
		}
	};
	
	function trimWords(value) {
		if (!value)
			return [""];
		if (!options.multiple)
			return [$.trim(value)];
		return $.map(value.split(options.multipleSeparator), function(word) {
			return $.trim(value).length ? $.trim(word) : null;
		});
	}
	
	function lastWord(value) {
		if ( !options.multiple )
			return value;
		var words = trimWords(value);
		if (words.length == 1) 
			return words[0];
		var cursorAt = $(input).selection().start;
		if (cursorAt == value.length) {
			words = trimWords(value)
		} else {
			words = trimWords(value.replace(value.substring(cursorAt), ""));
		}
		return words[words.length - 1];
	}
	
	// fills in the input box w/the first match (assumed to be the best match)
	// q: the term entered
	// sValue: the first matching result
	function autoFill(q, sValue){
		// autofill in the complete box w/the first match as long as the user hasn't entered in more data
		// if the last user key pressed was backspace, don't autofill
		if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
			// fill in the value (keep the case the user has typed)
			$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
			// select the portion of the value not typed by the user (so the next character will erase)
			$(input).selection(previousValue.length, previousValue.length + sValue.length);
		}
	};

	function hideResults() {
		clearTimeout(timeout);
		timeout = setTimeout(hideResultsNow, 200);
	};

	function hideResultsNow() {
		var wasVisible = select.visible();
		select.hide();
		clearTimeout(timeout);
		stopLoading();
		if (options.mustMatch) {
			// call search and run callback
			$input.search(
				function (result){
					// if no value found, clear the input box
					if( !result ) {
						if (options.multiple) {
							var words = trimWords($input.val()).slice(0, -1);
							$input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
						}
						else {
							$input.val( "" );
							$input.trigger("result", null);
						}
					}
				}
			);
		}
	};

	function receiveData(q, data) {
		if ( data && data.length && hasFocus ) {
			stopLoading();
			select.display(data, q);
			autoFill(q, data[0].value);
			select.show();
		} else {
			hideResultsNow();
		}
	};

	function request(term, success, failure) {
		if (!options.matchCase)
			term = term.toLowerCase();
		var data = cache.load(term);
		// recieve the cached data
		if (data && data.length) {
			success(term, data);
		// if an AJAX url has been supplied, try loading the data now
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){
			
			var extraParams = {};
			$.each(options.extraParams, function(key, param) {
				extraParams[key] = typeof param == "function" ? param() : param;
			});
			
			var url = options.url;
			var data = $.extend({
				q: lastWord(term),
				limit: options.max
			}, extraParams);
			
			if (options.useKeyValueURL) {
			    if (url.substring(url.length-1) != "/") {
			        url += "/";
			    }
    			$.each(data, function(key, param) {
    				url += key + "/" + escape(param) + "/";
    			});
    			url += "list.txt";
    			data = {};
			}

			$.ajax({
				// try to leverage ajaxQueue plugin to abort previous requests
				mode: "abort",
				// limit abortion to this input
				port: "autocomplete" + input.name,
				dataType: options.dataType,
				url: url,
				data: data,
				success: function(data) {
					var parsed = options.parse && options.parse(data) || parse(data);
					cache.add(term, parsed);
					success(term, parsed);
				}
			});
		} else {
			// if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
			select.emptyList();
			failure(term);
		}
	};
	
	function parse(data) {
		var parsed = [];
		var rows = data.split("\n");
		for (var i=0; i < rows.length; i++) {
			var row = $.trim(rows[i]);
			if (row) {
				row = row.split("|");
				parsed[parsed.length] = {
					data: row,
					value: row[0],
					result: options.formatResult && options.formatResult(row, row[0]) || row[0]
				};
			}
		}
		return parsed;
	};

	function stopLoading() {
		$input.removeClass(options.loadingClass);
	};

};

$.Autocompleter.defaults = {
	inputClass: "ac_input",
	resultsClass: "ac_results",
	loadingClass: "ac_loading",
	minChars: 1,
	delay: 400,
	matchCase: false,
	matchSubset: true,
	matchContains: false,
	cacheLength: 10,
	max: 100,
	mustMatch: false,
	extraParams: {},
	selectFirst: true,
	formatItem: function(row) { return row[0]; },
	formatMatch: null,
	autoFill: false,
	width: 0,
	multiple: false,
	multipleSeparator: ", ",
	highlight: function(value, term) {
		return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
	},
    scroll: true,
    scrollHeight: 180,
    useKeyValueURL: false
};

$.Autocompleter.Cache = function(options) {

	var data = {};
	var length = 0;
	
	function matchSubset(s, sub) {
		if (!options.matchCase) 
			s = s.toLowerCase();
		var i = s.indexOf(sub);
		if (options.matchContains == "word"){
			i = s.toLowerCase().search("\\b" + sub.toLowerCase());
		}
		if (i == -1) return false;
		return i == 0 || options.matchContains;
	};
	
	function add(q, value) {
		if (length > options.cacheLength){
			flush();
		}
		if (!data[q]){ 
			length++;
		}
		data[q] = value;
	}
	
	function populate(){
		if( !options.data ) return false;
		// track the matches
		var stMatchSets = {},
			nullData = 0;

		// no url was specified, we need to adjust the cache length to make sure it fits the local data store
		if( !options.url ) options.cacheLength = 1;
		
		// track all options for minChars = 0
		stMatchSets[""] = [];
		
		// loop through the array and create a lookup structure
		for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
			var rawValue = options.data[i];
			// if rawValue is a string, make an array otherwise just reference the array
			rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
			
			var value = options.formatMatch(rawValue, i+1, options.data.length);
			if ( value === false )
				continue;
				
			var firstChar = value.charAt(0).toLowerCase();
			// if no lookup array for this character exists, look it up now
			if( !stMatchSets[firstChar] ) 
				stMatchSets[firstChar] = [];

			// if the match is a string
			var row = {
				value: value,
				data: rawValue,
				result: options.formatResult && options.formatResult(rawValue) || value
			};
			
			// push the current match into the set list
			stMatchSets[firstChar].push(row);

			// keep track of minChars zero items
			if ( nullData++ < options.max ) {
				stMatchSets[""].push(row);
			}
		};

		// add the data items to the cache
		$.each(stMatchSets, function(i, value) {
			// increase the cache size
			options.cacheLength++;
			// add to the cache
			add(i, value);
		});
	}
	
	// populate any existing data
	setTimeout(populate, 25);
	
	function flush(){
		data = {};
		length = 0;
	}
	
	return {
		flush: flush,
		add: add,
		populate: populate,
		load: function(q) {
			if (!options.cacheLength || !length)
				return null;
			/* 
			 * if dealing w/local data and matchContains than we must make sure
			 * to loop through all the data collections looking for matches
			 */
			if( !options.url && options.matchContains ){
				// track all matches
				var csub = [];
				// loop through all the data grids for matches
				for( var k in data ){
					// don't search through the stMatchSets[""] (minChars: 0) cache
					// this prevents duplicates
					if( k.length > 0 ){
						var c = data[k];
						$.each(c, function(i, x) {
							// if we've got a match, add it to the array
							if (matchSubset(x.value, q)) {
								csub.push(x);
							}
						});
					}
				}				
				return csub;
			} else 
			// if the exact item exists, use it
			if (data[q]){
				return data[q];
			} else
			if (options.matchSubset) {
				for (var i = q.length - 1; i >= options.minChars; i--) {
					var c = data[q.substr(0, i)];
					if (c) {
						var csub = [];
						$.each(c, function(i, x) {
							if (matchSubset(x.value, q)) {
								csub[csub.length] = x;
							}
						});
						return csub;
					}
				}
			}
			return null;
		}
	};
};

$.Autocompleter.Select = function (options, input, select, config) {
	var CLASSES = {
		ACTIVE: "ac_over"
	};
	
	var listItems,
		active = -1,
		data,
		term = "",
		needsInit = true,
		element,
		list;
	
	// Create results
	function init() {
		if (!needsInit)
			return;
		element = $("<div/>")
		.hide()
		.addClass(options.resultsClass)
		.css("position", "absolute")
		.appendTo(document.body);
	
		list = $("<ul/>").appendTo(element).mouseover( function(event) {
			if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
	            active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
			    $(target(event)).addClass(CLASSES.ACTIVE);            
	        }
		}).click(function(event) {
			$(target(event)).addClass(CLASSES.ACTIVE);
			select();
			// TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
			input.focus();
			return false;
		}).mousedown(function() {
			config.mouseDownOnSelect = true;
		}).mouseup(function() {
			config.mouseDownOnSelect = false;
		});
		
		if( options.width > 0 )
			element.css("width", options.width);
			
		needsInit = false;
	} 
	
	function target(event) {
		var element = event.target;
		while(element && element.tagName != "LI")
			element = element.parentNode;
		// more fun with IE, sometimes event.target is empty, just ignore it then
		if(!element)
			return [];
		return element;
	}

	function moveSelect(step) {
		listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
		movePosition(step);
        var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
        if(options.scroll) {
            var offset = 0;
            listItems.slice(0, active).each(function() {
				offset += this.offsetHeight;
			});
            if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
                list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
            } else if(offset < list.scrollTop()) {
                list.scrollTop(offset);
            }
        }
	};
	
	function movePosition(step) {
		active += step;
		if (active < 0) {
			active = listItems.size() - 1;
		} else if (active >= listItems.size()) {
			active = 0;
		}
	}
	
	function limitNumberOfItems(available) {
		return options.max && options.max < available
			? options.max
			: available;
	}
	
	function fillList() {
		list.empty();
		var max = limitNumberOfItems(data.length);
		for (var i=0; i < max; i++) {
			if (!data[i])
				continue;
			var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
			if ( formatted === false )
				continue;
			var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
			$.data(li, "ac_data", data[i]);
		}
		listItems = list.find("li");
		if ( options.selectFirst ) {
			listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
			active = 0;
		}
		// apply bgiframe if available
		if ( $.fn.bgiframe )
			list.bgiframe();
	}
	
	return {
		display: function(d, q) {
			init();
			data = d;
			term = q;
			fillList();
		},
		next: function() {
			moveSelect(1);
		},
		prev: function() {
			moveSelect(-1);
		},
		pageUp: function() {
			if (active != 0 && active - 8 < 0) {
				moveSelect( -active );
			} else {
				moveSelect(-8);
			}
		},
		pageDown: function() {
			if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
				moveSelect( listItems.size() - 1 - active );
			} else {
				moveSelect(8);
			}
		},
		hide: function() {
			element && element.hide();
			listItems && listItems.removeClass(CLASSES.ACTIVE);
			active = -1;
		},
		visible : function() {
			return element && element.is(":visible");
		},
		current: function() {
			return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
		},
		show: function() {
			var offset = $(input).offset();
			element.css({
				width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
				top: offset.top + input.offsetHeight,
				left: offset.left
			}).show();
            if(options.scroll) {
                list.scrollTop(0);
                list.css({
					maxHeight: options.scrollHeight,
					overflow: 'auto'
				});
				
                if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
					var listHeight = 0;
					listItems.each(function() {
						listHeight += this.offsetHeight;
					});
					var scrollbarsVisible = listHeight > options.scrollHeight;
                    list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
					if (!scrollbarsVisible) {
						// IE doesn't recalculate width when scrollbar disappears
						listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
					}
                }
                
            }
		},
		selected: function() {
			var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
			return selected && selected.length && $.data(selected[0], "ac_data");
		},
		emptyList: function (){
			list && list.empty();
		},
		unbind: function() {
			element && element.remove();
		}
	};
};

$.fn.selection = function(start, end) {
	if (start !== undefined) {
		return this.each(function() {
			if( this.createTextRange ){
				var selRange = this.createTextRange();
				if (end === undefined || start == end) {
					selRange.move("character", start);
					selRange.select();
				} else {
					selRange.collapse(true);
					selRange.moveStart("character", start);
					selRange.moveEnd("character", end);
					selRange.select();
				}
			} else if( this.setSelectionRange ){
				this.setSelectionRange(start, end);
			} else if( this.selectionStart ){
				this.selectionStart = start;
				this.selectionEnd = end;
			}
		});
	}
	var field = this[0];
	if ( field.createTextRange ) {
		var range = document.selection.createRange(),
			orig = field.value,
			teststring = "<->",
			textLength = range.text.length;
		range.text = teststring;
		var caretAt = field.value.indexOf(teststring);
		field.value = orig;
		this.selection(caretAt, caretAt + textLength);
		return {
			start: caretAt,
			end: caretAt + textLength
		}
	} else if( field.selectionStart !== undefined ){
		return {
			start: field.selectionStart,
			end: field.selectionEnd
		}
	}
};

})(jQuery);