/*
 * jQuery File Upload Plugin JS Example 5.0
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://creativecommons.org/licenses/MIT/
 */

/*jslint nomen: false */
/*global $ */

$(function () {

    // Initialize the jQuery File Upload widget:
    $('#fileupload').fileupload({autoUpload:true});
	$('#fileupload').bind('fileuploadadd',
		function (e,data) {
		$('#diyimg').empty();
		$('#diyimg').addClass('loadview');
		}
	);

    $('#fileupload').bind('fileuploaddone',
    	function (e, data) {
			var newimgsrc = data.result[0].thumbnail_url;
			var newimgpath = data.result[0].newnamepath;
			$('.files').empty();
			setdiyimg(newimgsrc,newimgpath);
    	}
    );

    // Load existing files:
/*    $.getJSON($('#fileupload form').prop('action'), function (files) {
        var fu = $('#fileupload').data('fileupload');
        fu._adjustMaxNumberOfFiles(-files.length);
        fu._renderDownload(files)
            .appendTo($('#fileupload .files'))
            .fadeIn(function () {
                // Fix for IE7 and lower:
                $(this).show();
            });
    });*/

    // Open download dialogs via iframes,
    // to prevent aborting current uploads:
    $('#fileupload .files a:not([rel^=gallery])').live('click', function (e) {
        e.preventDefault();
        $('<iframe style="display:none;"></iframe>')
            .prop('src', this.href)
            .appendTo('body');
    });

	$('#zoomin').button({})
	.click(function(){
		zoomin();
	});

	$('#zoomout').button({})
	.click(function(){
		zoomout();
	});

	$('#createtext').button({})
	.click(function(){
		$('#createtext').removeClass('textbuttonpress');
		maketext();
	});
	
	$('.diytext').change(function() {
		$('#createtext').addClass('textbuttonpress');
	});

	$('#contestsubmit').button({}).click(function(){
	var im = $('#dimg')[0];	
	if (im != undefined){
		$('.submitbuttonspace').css('visibility','hidden');
		$('#submitparodyform').css('visibility','visible');
	}
	else {alert('Please upload an image to get started');}
	});
	
	$('#contestenter').button({}).click(function(){
		$('#capemail').removeClass('submitfix');
		var subem = $('#capemail')[0].value;
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		if(reg.test(subem) == false) {
			alert('Please enter a valid email to submit your parody to the contest.');
			$('#capemail').addClass('submitfix');
		} else {
			pagesetup.subemail = subem;
			pagesetup.subname = $('#subname')[0].value;
			pagesetup.suboptin = $('#wljoin')[0].value;
			saveimage('sub','stay');			
		}
	});
	

	$('#reorientL').button({})
	.click(function(){
		if (pagesetup.orientation != 'L'){
		$(this).css({borderColor: '#000'});
		$('#reorientP').css({borderColor: '#D3D3D3'});
		$('.skprod').removeClass('hideit');
		pagesetup.co();}
	});

	$('#reorientP').button({})
	.click(function(){
		if (pagesetup.orientation != 'P'){
		$(this).css({borderColor: '#000'});
		$('#reorientL').css({borderColor: '#D3D3D3'});
		$('.skprod').addClass('hideit');
		pagesetup.co();}
	});


	$('#dlimg').button({})
	.click(function(){
		saveimage('dl','stay');
	});
/*
	$('#mpimg').button({})
	.click(function(){
		saveimage('mp');
	});

	$('#cpimg').button({})
	.click(function(){
		saveimage('cp');
	});

	$('#dtimg').button({})
	.click(function(){
		saveimage('dt');
	});
*/
	$('#svimg').button({})
	.click(function(){
		saveimage('sv','stay');
	});


	maketext();
	$('#reorientL').css({borderColor: '#000'});
	
	$(".colors").miniColors({			
		change: function(hex, rgb) {
		if (this[0].id == 'colorTitle'){
		pagesetup.titlecolor = hex.replace('#','');
		} else if (this[0].id == 'colorTitle2') {
		pagesetup.captioncolor = hex.replace('#','');
		}
		}
		
	});
				
});

/*DIY functions*/

var pagesetup = {
	measurements: {	P:[574,650,432,449,424,441,503],
					L:[662,515,537,329,530,324,380]},
	prices: {
			diy301: '15.95',
			diy302: '15.95',
			dlts307: '19.95',
			dlts308: '19.95',
			dlts309: '19.95',
			dlts312: '19.95',			
			dlts314: '19.95',
			dlts315: '19.95',
			dlts317: '19.95'			
			},
	orientation: 'L',
	titlecolor: 'ffffff',
	captioncolor: 'ffffff',
	subemail: '',
	subname: '',
	suboptin: 0,
	saveimage: 'none',
	reset: function(){
		this.saveimage = 'none';
		$('.imagesharenotready').css('visibility','visible');
		$('.imagesharebuttons').css('visibility','hidden');		
	},
	co: function(){
		if (this.orientation == 'L')
			{
				this.orientation = 'P';
				this.resize();
			} 
			else {
				this.orientation = 'L'
				this.resize();
			}
	},
	resize: function(){
		this.reset();	
		var dcanvas = $('#diybase')[0];
		var dframe = $('#diyframe')[0];
		var dimg = $('#diyimg')[0];
		var dtitle = $('#titlebar')[0];
		var dtitletext = $('#showtext')[0];
		dcanvas.style.width = this.measurements[this.orientation][0]+'px';
		dcanvas.style.height = this.measurements[this.orientation][1]+'px';
		dframe.style.width = this.measurements[this.orientation][2]+'px';
		dframe.style.height = this.measurements[this.orientation][3]+'px';
		dimg.style.width = this.measurements[this.orientation][4]+'px';
		dimg.style.height = this.measurements[this.orientation][5]+'px';
//		dtitle.style.top = this.measurements[this.orientation][6]+'px';
//		dtitle.style.width = this.measurements[this.orientation][0]+'px';
//		dtitletext.style.width = this.measurements[this.orientation][0]+'px';
		maketext();
		checksize();
	}
	
	}

function maketext(){
	pagesetup.reset();
	var i = $('#imagelanding')[0];
	var c = $('#captionlanding')[0];
	var imgheight = 53;
	var capheight = 71;
	var bor = $('#diyframe')[0];
	var tcol = $('#titlecolor')[0];
	var ccol = $('#captioncolor')[0];
	var tcolv = pagesetup.titlecolor;
	var ccolv = pagesetup.captioncolor;
	var s = 60; //title font size
	var cs = 15; //caption font size
	var texttoformat = $('#texttoformat')[0];
	var t = texttoformat.value;
	var textfont = $('#textfont')[0];
	var f = escape(textfont.value);
	var caption1 = $('#textline1')[0];
	var caption2 = '';//$('#textline2')[0];
	var captionfont = $('#captionfont')[0];
	var tc1 = caption1.value.replace(/(\r\n|\n|\r)/gm,"|||");
	var tc1 = escape(tc1);
	var tc2 = '';//escape(caption2.value);
	var cf = captionfont.value;
	var url = 'builders/textbuilder.php?t='+t+'&f='+f+'&s='+s+'&o='+pagesetup.orientation+'&c='+tcolv+'&imgh='+imgheight+'&imgw='+pagesetup.measurements[pagesetup.orientation][0];
	var curl = 'builders/captionbuilder.php?t1='+tc1+'&t2='+tc2+'&f='+cf+'&s='+cs+'&o='+pagesetup.orientation+'&c='+ccolv+'&imgh='+capheight+'&imgw='+pagesetup.measurements[pagesetup.orientation][0];
	i.setAttribute('src',url);
	c.setAttribute('src',curl);
	bor.style.borderColor = '#'+tcolv;
}

function zoomin(){
	if ($('#dimg')[0]){
	pagesetup.reset();
	var im = $('#dimg')[0];
	im.style.width = (im.width*1.1)+'px';
	im.style.height = (im.height*1.1)+'px';
	}
}

function zoomout(){
	if ($('#dimg')[0]){
	var im = $('#dimg')[0];
	var imbox = $('#diyimg')[0];
	var imratio = im.naturalWidth/im.naturalHeight;
	if (((im.width*.9) >=imbox.offsetWidth) && ((im.height*.9) >=imbox.offsetHeight))
	{
		pagesetup.reset();
		im.style.width = (im.width*.9)+'px';
		im.style.height = (im.height*.9)+'px';
		checkdims();
	} else {checksize();alert('Your image can not zoom out any more.')}
	}
}

function setdiyimg(newimg,newpath){
	pagesetup.reset();
	$('#diyimg').removeClass('loadview');
	$('#diyimg').empty();
	var i = document.createElement('img');
	i.setAttribute('src',newpath+newimg);
	i.setAttribute('id','dimg');
	$('#diyimg').append(i);
	$('#dimg').load(function() {
		checksize();
	});
	$('#dimg').draggable({
		stop: function(event,ui) {
			 checkdims();
		}
	});
}

function checksize(){
	var im = $('#dimg')[0];
	var imbox = $('#diyimg')[0];
	if (im != undefined){
	pagesetup.reset();
	var imratio = im.naturalWidth/im.naturalHeight;
	var resizeheight = 0;
	var resizewidth = 0;
	if ((imbox.offsetWidth/imratio) < imbox.offsetHeight) {
		resizeheight = imbox.offsetHeight;
		resizewidth = resizeheight*imratio;
	} else {
		resizewidth = imbox.offsetWidth;
		resizeheight = resizewidth/imratio;
	}

	im.style.width = resizewidth+'px';
	im.style.height = resizeheight+'px';
	checkdims();}
}

function checkdims(){
	pagesetup.reset();
	var im = $('#dimg')[0];
	var imbox = $('#diyimg')[0];
	if (im.offsetLeft > 0) 
	{
		im.style.left = '0px';
	} else { 
		if ((im.offsetLeft + im.width) < imbox.offsetWidth) {im.style.left = (imbox.offsetWidth-im.width)+'px';}
	}
	if (im.offsetTop > 0)
	{
		im.style.top = '0px';
	} else {
		if ((im.offsetTop + im.height) < imbox.offsetHeight) {im.style.top = (imbox.offsetHeight-im.height)+'px';}
	}					
}

function saveimage(choice,sku){
var im = $('#dimg')[0];
if (im != undefined){
		$('#loadstatus').addClass('loadview');		
		var imbox = $('#diyimg')[0];
		var imgheight = 60;
		var posturl = 'http://order.store.yahoo.net/cgi-bin/wg-order?demotivators+';
		var capheight = 80;
		var i = $('#imagelanding')[0];
		var c = $('#captionlanding')[0];
		var st = (im.offsetTop - 4)/im.offsetHeight; //start top for crop - 4 is the offset start value
		var sl = (im.offsetLeft - 4)/im.offsetWidth;
		var hi = imbox.offsetHeight/im.offsetHeight;
		var wi = imbox.offsetWidth/im.offsetWidth;
		var f = 'SHARE';
		var img = im.src;
		var tcolv = pagesetup.titlecolor;
		var ccolv = pagesetup.captioncolor;
		var s = 60; //title font size
		var cs = 15; //caption font size
		var texttoformat = $('#texttoformat')[0];
		var t = texttoformat.value;
		t = escape(t);
		var textfont = $('#textfont')[0];
		var tf = escape(textfont.value);
		var caption1 = $('#textline1')[0];
		var caption2 = '';//$('#textline2')[0];
		var captionfont = $('#captionfont')[0];
		var tc1 = caption1.value.replace(/(\r\n|\n|\r)/gm,"|||");
		tc1 = escape(tc1);
		var tc2 = '';//escape(caption2.value);
		var cf = captionfont.value;
		var url = '';
		var destination = choice;
		if ((choice == 'mp') || (choice == 'cp') || (choice == 'dt')) {destination = 'buy';}

	if (pagesetup.saveimage == 'none'){
		$.ajax({
			url:'builders/saveimage.php?st='+st+'&sl='+sl+'&hi='+hi+'&wi='+wi+'&img='+img+'&tc='+tcolv+'&o='+pagesetup.orientation+'&f='+f+'&t='+t+'&tf='+tf+'&s='+s+'&tc1='+tc1+'&tc2='+tc2+'&cf='+cf+'&cs='+cs+'&ccolv='+ccolv+'&imgh='+imgheight+'&caph='+capheight+'&imgw='+pagesetup.measurements[pagesetup.orientation][0],
			success: function(data)
			{
			var response = data || "none";
			pagesetup.saveimage = response;
			if (pagesetup.saveimage != 'none'){
				switch (destination) {
				case 'sub':
					{
					$.ajax({
						url:'builders/submitparody.php',
						type:'POST', data:{submission:pagesetup.saveimage,subemail:pagesetup.subemail,subopt:pagesetup.suboptin,subname:pagesetup.subname},
						success: function(data){var response = data;
							alert(response);//alert('Thank you for your submission.  Follow Despair on Facebook at http://www.facebook.com/DespairInc to see the winners.  We will email you if you win.');
						}
					
					});
					$('#loadstatus').removeClass('loadview');		
					break;
					};
				case 'dl':
					{
					url = 'builders/downloadpic.php?n='+pagesetup.saveimage;
					window.location.href = url;
					$('#loadstatus').removeClass('loadview');		
					break;
					};
				case 'sv':
					{
					$.ajax({
						url:'builders/sharepage.php',
						type:'POST',
						data:{saveimg:pagesetup.saveimage},
						success: function(data){var response = data; 
						/*populate social media buttons with info*/
							$('.fb_share_link')[0].setAttribute('href','http://www.facebook.com/share.php?u=www.whatabeets.com/aws/builders/share/'+response+'.html');
							var twlink = 'http://diy.despair.com/builders/share/'+response+'.html';
							$('.twitterlink')[0].setAttribute('href','http://www.twitter.com?status='+twlink);
							$('.imagesharenotready').css('visibility','hidden');
							$('.imagesharebuttons').css('visibility','visible');
							$('#loadstatus').removeClass('loadview');						
						}
					});
					break;
					};
				case 'buy':
					{
					$.ajax({
					url:'builders/saveimage.php',
					type:'POST',
					data:{saveimg:pagesetup.saveimage,format:choice},
					success: function(data){
						var response = data; 
						if (response.indexOf('Cannot') > 0){
							alert('Add to cart did not work - please try again');
							$('#loadstatus').removeClass('loadview');		
							} else {											
							var slashloc = response.lastIndexOf('/');
							response = response.slice(slashloc+1);
							$('#ysForm')[0].setAttribute('action',posturl+'sku');
							$('#vwitem')[0].setAttribute('value',sku);
							$('#vwprice')[0].setAttribute('value',pagesetup.prices[sku.replace(/\-/,"")]);
							$('#DiyAsset')[0].setAttribute('value',response);	
							$('#Title')[0].setAttribute('value',texttoformat.value);
							$('#Caption')[0].setAttribute('value',caption1.value);
							$('#ysForm')[0].submit();
							$('#loadstatus').removeClass('loadview');		
							}
						}
					});
					break;
					};

		/*		case 'tw':
					{
					new Ajax.Request('sharepage.php',{method:'post',onSuccess: function(transport){var response = transport.responseText; twit(response);},parameters:{saveimg:pagesetup.saveimage,title:t}});
					break;
					};
				case 'fb':
					{
					new Ajax.Request('sharepage.php',{method:'post',onSuccess: function(transport){var response = transport.responseText; fbs_click(t,response);},parameters:{saveimg:pagesetup.saveimage,title:t}});
					break;
					};*/
				default:
					break;		
				}
			} else {alert('There seems to be a problem with the image save.  Please try again later.');}
			}
			});
		} 
		else {
		switch (destination) {
				case 'sub':
					{
					$.ajax({
						url:'builders/submitparody.php',
						type:'POST', data:{submission:pagesetup.saveimage,subemail:pagesetup.subemail,subopt:pagesetup.suboptin,subname:pagesetup.subname},
						success: function(data){var response = data;
							alert(response);//alert('Thank you for your submission.  Follow Despair on Facebook at http://www.facebook.com/DespairInc to see the winners.  We will email you if you win.');
						}
					
					});
					$('#loadstatus').removeClass('loadview');		
					break;
					};
			case 'dl':
				{
				url = 'builders/downloadpic.php?n='+pagesetup.saveimage;
				window.location.href = url;
				$('#loadstatus').removeClass('loadview');		
				break;
				};
				
				case 'buy':
					{
					$.ajax({
					url:'builders/saveimage.php',
					type:'POST',
					data:{saveimg:pagesetup.saveimage,format:choice},
					success: function(data){
						var response = data; 
						if (response.indexOf('Cannot') > 0){
							alert('Add to cart did not work - please try again');
							$('#loadstatus').removeClass('loadview');		
							} else {											
							var slashloc = response.lastIndexOf('/');
							response = response.slice(slashloc+1);
							$('#ysForm')[0].setAttribute('action',posturl+'sku');
							$('#vwitem')[0].setAttribute('value',sku);
							$('#vwprice')[0].setAttribute('value',pagesetup.prices[sku.replace(/\-/,"")]);
							$('#DiyAsset')[0].setAttribute('value',response);	
							$('#Title')[0].setAttribute('value',texttoformat.value);
							$('#Caption')[0].setAttribute('value',caption1.value);
							$('#ysForm')[0].submit();
							$('#loadstatus').removeClass('loadview');		
							}
						}
					});
					break;
					};
				case 'sv':
					{
					$.ajax({
						url:'builders/sharepage.php',
						type:'POST',
						data:{saveimg:pagesetup.saveimage},
						success: function(data){var response = data; 
						/*populate social media buttons with info*/
							$('.fb_share_link')[0].setAttribute('href','http://www.facebook.com/share.php?u=www.whatabeets.com/aws/builders/share/'+response+'.html');
							var twlink = 'http://diy.despair.com/builders/share/'+response+'.html';
							$('.twitterlink')[0].setAttribute('href','http://www.twitter.com?status='+twlink);
							$('.imagesharenotready').css('visibility','hidden');
							$('.imagesharebuttons').css('visibility','visible');
							$('#loadstatus').removeClass('loadview');						
						}
					});
					break;
					};
				
/*				case 'tw':
					{
					new Ajax.Request('sharepage.php',{method:'post',onSuccess: function(transport){var response = transport.responseText; twit(response);},parameters:{saveimg:pagesetup.saveimage,title:t}});
					break;
					};
				case 'fb':
					{
					new Ajax.Request('sharepage.php',{method:'post',onSuccess: function(transport){var response = transport.responseText; fbs_click(t,response);},parameters:{saveimg:pagesetup.saveimage,title:t}});
					break;
					};*/
				default:
					break;				
			}	
		}
		} else {alert('Please upload an image to get started');}
}
