/***** image dimensions from http://lucassmith.name/2008/11/is-my-image-loaded.html *****/

// First a couple helper functions
function spGet(id) {
    return !id || id.nodeType === 1 ? id : document.getElementById(id);
}
function isType(o,t) {    return (typeof o).indexOf(t.charAt(0).toLowerCase()) === 0;}

// Here's the meat and potatoes
function image(src,cfg) {    var img, prop, target;
    cfg = cfg || (isType(src,'o') ? src : {});

    img = spGet(src);
    if (img) {
        src = cfg.src || img.src;
    } else {
        img = document.createElement('img');
        src = src || cfg.src;
    }

    if (!src) {
        return null;
    }

    prop = isType(img.naturalWidth,'u') ? 'width' : 'naturalWidth';
    img.alt = cfg.alt || img.alt;

    // Add the image and insert if requested (must be on DOM to load or
    // pull from cache)
    img.src = src;

    target = spGet(cfg.target);
    if (target) {
        target.insertBefore(img, spGet(cfg.insertBefore) || null);
    }

    // Loaded?
    if (img.complete) {
        if (img[prop]) {
            if (isType(cfg.success,'f')) {
                cfg.success.call(img);
            }
        } else {
            if (isType(cfg.failure,'f')) {
                cfg.failure.call(img);
            }
        }
    } else {
        if (isType(cfg.success,'f')) {
            img.onload = cfg.success;
        }
        if (isType(cfg.failure,'f')) {
            img.onerror = cfg.failure;
        }
    }

    return img;
}

/***** setup *****/
/*
function setupTogglers() {
	var togglersMore = $('.toggler-more');
	var togglersLess = $('.toggler-less');
	if((togglersMore.length > 0)){
		togglersMore.click(function(){
			var toggler = $(this);
			$(toggler.attr('href')).animate({height:'toggle'},100);
			toggler.hide();
			return false;
		});
	}
	if((togglersLess.length > 0)){
		togglersLess.click(function(){
			var toggler = $(this);
			var prevToggler = toggler.parents('#info').find('.toggler-more');
			$(toggler.attr('href')).animate({height:'toggle'},100);
			prevToggler.show();
			return false;
		});
	}
}
*/

function setupTogglers() {
	var togglersMore = $('.toggler-more');
	var togglersLess = $('.toggler-less');
	if((togglersMore.length > 0)){
		togglersMore.click(function(){
			
			var id = $(this).parent().parent().attr("id").replace("summary_", "");
			$("#summary_" + id).hide();
			$("#all_" + id).show();
			return false;
		
			/*
			$('#info-part').hide();
			$('#info-more').show();
			return false;
			*/
		});
	}
	if((togglersLess.length > 0)){
		togglersLess.click(function(){

			var id = $(this).parent().parent().attr("id").replace("all_", "");
			$("#all_" + id).hide();
			$("#summary_" + id).show();
			return false;			
			/*
			$('#info-more').hide();
			$('#info-part').show();
			return false;
			*/
		});
	}
}

function setupHomeCaptions() {
	var homeImages = $('#home-images li a');
	if(homeImages.length > 0){
		homeImages.hover(
			function () {
				$(this).children('span').animate({opacity:'show'},100);
			},
			function () {
				$(this).children('span').animate({opacity:'hide'},100);
			}
		);
	}
}

function setupScrolling() {
	var scroller = $('.scroller');
	if(scroller.length > 0){
		scroller.click(function(){
			$.scrollTo($(this).attr('href'),100);
			return false;
		});
	}
}
	
function setupMessage() {
	var messageClose = $('.message a.close');
	if(messageClose.length > 0){
		messageClose.click(function(){
			$(this).parent().animate({opacity:'hide'},300);
			return false;
		});	
	}
}

function setupExtLinks() {
	var links = $('a.ext');
	if (links.length > 0) {
		links.click(function() {
			window.open(this.href);
			return false;
		});
	}
}

function setupHomeImages() {
	var homeImages = $('#home-images img');
	if(homeImages.length > 0) {
		homeImages.each(function(){
			image(this,{
			    success : function () { 
			    	var imgWidth = this.width;
			    	var imgHeight = this.height;
			    	var parentWidth = $(this).parent().width(); 
			    	var parentHeight = $(this).parent().height(); 
			    	if(imgWidth > imgHeight){
			    		// image is horizontal
			    		var imgRatio =  imgWidth / imgHeight;
						this.height = parentHeight;
						// make sure image covers full parent width
						if(this.width < parentWidth){
							this.width = parentWidth;
							this.height = this.width / imgRatio;
						}
						// center image horizontally
						$(this).attr('style','left:50%;margin-left:-' + ($(this).width() * 0.5) + 'px');
			    	} else {
			    		// image is vertical
			    		var imgRatio =  imgHeight / imgWidth;
						this.width = parentWidth;
						// make sure image covers full parent height
						if(this.height < parentHeight){
							this.height = parentHeight;
							this.width = this.height / imgRatio;
						}
						// center image vertically
						$(this).attr('style','top:50%;margin-top:-' + ($(this).height() * 0.5) + 'px');
			    	}
			    }
			});
		});		
	}
}

function pagenav(uri, params, replace_id) {
	$.ajax({
		type: "GET",
		url: uri,
		data: params,
		success: function(data) {
			$("#" + replace_id).html(data);
		}
	});
}

function setupAutoTags() {
	$('.autotag').click(function() {
		var tags = $("#tag_box").val();
		if (typeof(tags) != 'undefined')
			$("#tag_box").val(tags + (tags.length > 0 ? ", " : "") + $(this).text());
	});
}

function initImageUpload(uri, input, id) {
	id = id ? id : false;
	
	$(function(){  
		var btnUpload=$("#upload_" + input);  
		var status=$("#status_" + input);
		new AjaxUpload(btnUpload, {  
			action: uri,
			data: {id: id ? $("#" + id).value : ""},
			//Name of the file input box  
			name: input,  
			onSubmit: function(file, ext){  
				if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {  
					// check for valid file extension  
					status.text('Only JPG, PNG or GIF files are allowed');  
					return false;  
				}  
				status.text('Uploading...');
				return true;
			},  
			onComplete: function(file, response) {

				response = JSON.parse(response);
				
				//On completion clear the status  
				status.text('');
				
				if (response['status'] != "success")
					status.text(response['message']);
				else {
					$('<li></li>').appendTo('#' + input).html('<img src="'+response['file']+'" alt="" />');
					
					if (id)
						$("#" + id).val(response[id]);
				}
				/*
				//Add uploaded file to list  
				if(response==="success") {  
					$('<li></li>').appendTo('#' + input).html('<img src="./uploads/'+file+'" alt="" /><br />'+file).addClass('success');  
				}
				else {  
					$('<li></li>').appendTo('#' + input).text(file).addClass('error');  
				}
				*/
			}  
		});  
	});

}

$(document).ready(function(){
	$('body').removeClass('nojs');
	setupTogglers();
	setupHomeCaptions();
	setupZoom();
	setupScrolling();
	setupMessage();
	setupHomeImages();
	setupAutoTags();
	setupExtLinks();
	
	$('#photos div.options a').each(function() {
		$(this).click(function() {
			var temp = $(this).attr("class").split("_");
			var id = temp[temp.length-1];
			
			var remove_input = "<input type=\"hidden\" name=\"remove_photo[]\" value=\"" + id + "\">";
			$('#options_' + id).append(remove_input);
			
			$('#photo_' + id).hide();
			return false;
		});
	});

	/*
	//$('#photos a div').hide();
	$('#photos a img').hover(
		// in
		function() {
			var id = $(this).attr('id').replace("upload_photo_", "");
			$('#options_' + id).show();
		},
		// out
		function () {
			var id = $(this).attr('id').replace("upload_photo_", "");
			$('#options_' + id).hide();
		}
	);
	*/
});

