$(document).ready(function(){
	
	
	function isiProduct(){
	    return (
	        (navigator.platform.indexOf("iPhone") != -1) ||
	        (navigator.platform.indexOf("iPod") != -1) ||
	        (navigator.platform.indexOf("iPad") != -1)
	    );
	}
	
	function renderLayout(){
		$('#layout').css({
			height: window.innerHeight
		});
		//$('#charlieStore').css({width:window.innerWidth-parseInt($('#leftNav').css('width')), height: $('#layout #content').css('height')-10});
	}
	$(window).resize(function(){
		renderLayout();
	});
	renderLayout();


	$('#logoFront, #logoBack').click(function(){
		window.location="http://charliee.com/";
	});
	$('#layout #content a').addClass('transition');
	
	if(isiProduct()){
		$(window).scroll(function(){
			$('#logoContainer').stop().animate({
				marginTop: ((parseInt($('html').offset().top))*-1)+9
			}, 1000);
		});
	} else {
		console.log('Not an iProduct!');
	}
	
	
    $('#leftNav').wrapInner('<div id="lContainer" />');
	
	$('#uploadImages, #uploadGallery').click(function(e){
		e.preventDefault();
		$('#imUlForm').submit();
	});
	
	try{
		$('a[rel='+curPage+']').addClass('active');
	}catch (e){}
	
	
	$('#sendMail').click(function(e){
		e.preventDefault();
		$('#mailHouse').fadeTo(1000, 0, function(){
			$(this).animate({
				height:'12px'
			}, 1000, function(){
				$.ajax({
					url:'includes/email.php',
					type:'POST',
					data: {
						salt: 'sugar',
						name: $('#name').val(),
						email: $('#email').val(),
						message: $('#message').val()
					},
					success: function(data){
						if(data=="sent"){
							$('#mailHouse').html('Thank You');
						} else if(data=="failed"){
							$('#mailHouse').html('Your message was not delivered');
						}
						$('#mailHouse').fadeTo(1000, 1);
					}
				});
			});
		});
	});
	
	$('.imageLink').click(function(){
		window.location=$(this).text();
	});
	
	$('.deleteImage').click(function(){
		if(confirm('Delete this Photo?')){
			var curRow = $(this).parent();
			$.ajax({
				url:'includes/imgUpload.php',
				data: {action: 'delete', id: curRow.attr('id')},
				success: function(data){
					if(data=="success"){
						curRow.fadeOut(300, function(){
							$(this).remove();
						});
					}
				}
			});
		}
	});
	
	$('.deleteGalleryImage').click(function(){
		if(confirm('Delete this Photo?')){
			var curRow = $(this).parent();
			$.ajax({
				url:'includes/galleryUpload.php',
				data: {action: 'delete', id: curRow.attr('id')},
				success: function(data){
					if(data=="success"){
						curRow.fadeOut(300, function(){
							$(this).remove();
						});
					}
				}
			});
		}
	});
	
	$('.deletePost').click(function(){
		if(confirm('Delete this Post?')){
			var curRow = $(this).parent().parent();
			$.ajax({
				url: 'includes/postTools.php',
				data: {action: 'delete', id: curRow.attr('id')},
				success: function(data){
					if(data=="success"){
						curRow.fadeOut(300, function(){
							$(this).remove();
						});
					}
				}
			});
		}
	});
	$('.deleteWork').click(function(){
		if(confirm('Delete this Work?')){
			var curRow = $(this).parent().parent();
			$.ajax({
				url: 'includes/postTools.php',
				data: {action: 'deleteWork', id: curRow.attr('id')},
				success: function(data){
					if(data=="success"){
						curRow.fadeOut(300, function(){
							$(this).remove();
						});
					}
				}
			});
		}
	});
	$('#savePost').click(function(e){
		e.preventDefault();
		$.ajax({
			url: 'includes/postTools.php',
			type: 'POST',
			data: {action: 'savePost', title: $('#postTitle').val(), content: $('.nicEdit-main').html()},
			success: function(data){
				window.location="./newsEdit.php?saved";
			}
		});
	});
	
	$('#updatePost').click(function(e){
		e.preventDefault();
		var targetPost = $('#hiddenID').val();
		$.ajax({
			url: 'includes/postTools.php',
			type: 'POST',
			data: {action: 'updatePost', title: $('#postTitle').val(), content: $('.nicEdit-main').html(), id: targetPost},
			success: function(data){
				if(data=="success"){
					window.location="./newsEdit.php?updated";
				}
			}
		});
	});
	
	
	$('#updateAbout').click(function(e){
		e.preventDefault();
		$.ajax({
			url: 'includes/postTools.php',
			type: 'POST',
			data: {
				action: 'updateAbout',
				content: $('.nicEdit-main').html()
			},
			success: function(data){
				if(data=="success"){
						window.location="./aboutEdit.php?updated";
				} else {
					console.log(data);
				}
			}
		});
	});
    
	$('#saveWork').click(function(e){
        e.preventDefault();
        $.ajax({
            url: 'includes/postTools.php',
			type: 'POST',
			data: {
				action: 'saveWork', 
				type: $('#type').val(),
				name: $('#name').val(),
				year: $('#year').val(),
				medium: $('#medium').val(),
				size: $('#size').val(),
				notes: $('#notes').val(),
				content: $('.nicEdit-main').html()
			},
			success: function(data){
				if(data=="success"){
					window.location="./workEdit.php?saved";
				}
			}
		});
	});
    
	$('#updateWork').click(function(e){
		e.preventDefault();
		var targetPost = $('#hiddenID').val();
		$.ajax({
			url: 'includes/postTools.php',
			type: 'POST',
			data: {
				action: 'updateWork', 
				type: $('#type').val(),
				name: $('#name').val(),
				year: $('#year').val(),
				medium: $('#medium').val(),
				size: $('#size').val(),
				notes: $('#notes').val(),
				content: $('.nicEdit-main').html(),
				id: targetPost
			},
			success: function(data){
				if(data=="success"){
					window.location="./workEdit.php?updated";
				}
			}
		});
	});
	
	
	
	$('#doLogin').click(function(e){
		e.preventDefault();
		$.ajax({
			url: 'login.php',
			type: 'POST',
			data: {doLogin: true, username: $('#uLogin').val(), password: $('#pLogin').val()},
			success: function(data){
				if(data=="success"){
					window.location="index.php";
				} else {
					alert('Invalid username or password');
				}
			}
		});
	});
	
	$('#pLogin').keydown(function(e){
		if(e.which==13){
			e.preventDefault();
			$('#doLogin').click();
		}
	});
	
	$('.editPost, .editWork').click(function(){
		window.location="?id="+$(this).parent().parent().attr('id');
	});
	$('.imgHandle').click(function(e){
		$('.nicEdit-main').append('<img src="'+$(this).attr('rel')+'" class="postImg" />');
	});
	$('.blockLinks a').attr({'target':'_blank'});
	$('#storeLink').click(function(e){
		e.preventDefault();
		$('#content').html('<iframe src="http://store.charliee.com/" frameborder="0" width="100%" height="100%"></iframe>');
	});
	
	
	
	
	$('#workHandle').click(function(){
		if($('.extraNav').css('height')!='75px'){
			$('.extraNav').stop().animate({
				height:'75px'
			}, function(){
				$('.extraLinks').stop().fadeTo(300, 1);
			});
		} else {
			$('.extraLinks').stop().fadeTo(300, 0, function(){
				$('.extraNav').stop().animate({
					height:'25px'
				});
			});
		}
	});
	
	$('#increaseIStreamSize').click(function(){
		$('#imageStream').css({width:'+=60px'});
	});
	$('#decreaseIStreamSize').click(function(){
		$('#imageStream').css({width:'-=60px'});
	});
	
	var fixHelper = function(e, ui) {
        ui.children().each(function() {
            $(this).width($(this).width());
        });
        return ui;
	};
	
	function getTableOrder(tableID, doPage){
        var rows = [];
		$('#'+tableID+' tr').each(function(){
			rows.push(this.id);
		});
		$.ajax({
			url:'includes/updateOrder.php',
			type:'POST',
			data: {order:rows, page: doPage}
		});
	}
	
	var colspan = 4;
	var sortState='sortState';
	if($('#fileTable').attr('rel')=="work"){
		colspan=6;
	}
	if($('#fileTable').attr('rel')=="gallery"){
		colspan=5;
		sortState='sortStateGallery';
	}
	
	try{
	$('#fileTable:not(.artTable) tbody').sortable({ 
		helper: fixHelper,
		placeholder: sortState,
		'start': function (event, ui) {
            $('.sortState').html('<td colspan="'+colspan+'">&nbsp;</td>');
        },
        items:'tr',
        axis:'y',
        cursorAt: { left: 5 },
		update: function() {
			getTableOrder('fileTable', $('#fileTable').attr('rel'));
		}
	});
	$('#fileTable:not(.artTable) tbody').disableSelection();
    } catch(er){}
	
	
	$('#slideshow, #galleryControls').hover(function(){
		$('#galleryControls').stop().fadeTo(300, 1);
	}, function(){
		$('#galleryControls').stop().fadeTo(300, 0);
	});
	
	try{
		$('.imgHandle img').hover(function(){
			$('#imageSize').html('Size: '+$(this).attr('rel'));
		});
	} catch(err){
	}
	
    var currentImage = null;
    
    $('#toggleBorder').click(function(e){
        e.preventDefault();
        
        if(!currentImage){
            alert('Select an image first, yo!');
            return;
        }
        
        if(currentImage.hasClass('customBorder')){
            currentImage.removeClass('customBorder');
        } else {
            currentImage.addClass('customBorder');
        }
    });
    
    $('#toggleShadow').click(function(e){
        e.preventDefault();
        
        if(!currentImage){
            alert('Select an image first, yo!');
            return;
        }
        
        if(currentImage.hasClass('customShadow')){
            currentImage.removeClass('customShadow');
        } else {
            currentImage.addClass('customShadow');
        }
    });
    
    $('#toggleLightShadow').click(function(e){
        e.preventDefault();
        
        if(!currentImage){
            alert('Select an image first, yo!');
            return;
        }
        
        if(currentImage.hasClass('customLightShadow')){
            currentImage.removeClass('customLightShadow');
        } else {
            currentImage.addClass('customLightShadow');
        }
    });
    
    $('.nicEdit-main img.postImg').live('click', function(){
        currentImage=$(this);
    });
    
    $('#addReadMore').live('click', function(e){
        e.preventDefault();
        $('.nicEdit-main').append('<div class="readMore"></div>');
    });
    
    try{var tempReset = subPage;}catch(e){var subPage='tempReset';}
    
    if($('#addReadMore').length!=1){
        $('.readMore').css({display:'none'});
        if(subPage=="design"){
        	$('.readMore').before('<a href="javascript:void(0);" class="readMoreLink">View Full Project</a>');
        } else {
        	$('.readMore').before('<a href="javascript:void(0);" class="readMoreLink">View More</a>');
        }
    }
    $('a.readMoreLink').live('click', function(){
        var targetElem = $(this).next();
        var preloadImages = targetElem.find('img');
        preloadImages.each(function(i){
            $(this).attr({'src' : $(this).attr('original')});
            $(this).removeAttr('original');
        });
        
        targetElem.slideDown(500);
        
        if(subPage=="design"){
        	targetElem.after('<a href="javascript:void(0);" class="hideMoreLink">Hide Full Project</a>');
        } else {
        	targetElem.after('<a href="javascript:void(0);" class="hideMoreLink">View Less</a>');
        }
        $(this).fadeOut(500, function(){
        	$(this).remove();
        });
    });
    
    $('a.hideMoreLink').live('click', function(){
        $(this).prev().slideUp(500, function(){
        	window.location='#'+$(this).parent().parent().attr('id');
        	console.log($(this).parent().parent().attr('id'));
        	
        });
        $(this).fadeOut(500, function(){
        	$(this).remove();
        });
        if(subPage=="design"){
        	$(this).prev().before('<a href="javascript:void(0);" class="readMoreLink">View Full Project</a>');
        } else {
        	$(this).prev().before('<a href="javascript:void(0);" class="readMoreLink">View More</a>');
        }
    });
    
});
