if(typeof(window.JQ)=="undefined"){var JQ = jQuery.noConflict();}

// f4a Ajax Helper method
function swfAjaxRequest(url, method, data, callback){
	this.url = url || '';
	this.method = method || 'POST';
	this.data = data || {};
	this.callback = callback || function(){ alert('No callback provided'); };
	this.req = {'url':this.url,'meth':this.method,'data':this.data,'onready':function(data){ callback(data); }};
	this.sendRequest = function() { f4a.open(this.req); };
}

function embedFileUploader(elementId){
	var currentTime = new Date();
	var so = new SWFObject("/nikeos/global/modules/profile_image_upload/v1/swf/uploader22.swf", 'uploader', "140", "14", "9", "#aaaaaa");
	so.addParam("wmode", "transparent");
	so.addParam("allowScriptAccess", "always");
	so.write(elementId);
	moveOverLink(JQ('#'+elementId),JQ('#profile_caption a:visible'))
}


function moveOverLink(swf,ele){
	

    var posX = ele.offset({ border: true, padding: true }).left; 
    var posY = ele.offset({ border: true, padding: true }).top;	
	if (jQuery.browser.msie && (jQuery.browser.version < 7)){
        posY = posY - 15; 
    }
	swf.css({top:posY+'px', left:posX+'px', width:'140px',height:'14px',position:'absolute'});
	//swf.data('z-index':swf.css(zIndex));
	
	
	
}



//Used to dispatch events to uploader.swf
var uploadUtils = {
	'browse' : function(){
		var arrFilters = new Array();
		var objFilter = {
			'description' : "Images (*.jpg, *.jpeg, *.png)",
			'extension' : "*.jpg;*.jpeg;*.png"
		};
		arrFilters.push(objFilter);
		var objData = {
			'filters' : arrFilters
		};
		EventBridge.dispatchEvent({type:"onFileBrowse", data:objData});
	},
	
	'upload' : function(){
		if(JQ('#image_file_name').val() != ""){
			var strUploadPath = UPM.UPLOAD_URL + "&locale=" + UPM.locale;
			var strFieldName = "Filedata";
			EventBridge.dispatchEvent({type:"onFileUpload", data:{uploadPath:strUploadPath, fieldName:strFieldName}});
			JQ.blockUI();
		}
		else {
			console.log('No File Entered');
		}
	}
};

//Listens for events fired by uploader.swf
var uploadListener = {
	'onUploadFileSelect' : function(obj){
		console.log('onUploadFileSelect called');
		var strName = obj.data.name;
		var nSize = obj.data.size;
		console.log('name: '+obj.data.name+' & size: '+obj.data.size);
		if (nSize > 400000)
		{
			//clear text box
			alert("Oops.  Looks like your pic is over 400kb.  We are sure its awesome, so try scaling it down and uploading again.");
			JQ('#image_file_name').val("");
		}
		else
		{
			//automatically upload image if it is valid.
			JQ('#image_file_name').val(strName);
			uploadUtils.upload();
		}
	},
	
	'onUploadCompleteData' : function(obj){
		var responseText = obj.data.response;
		var responseJSON = JQ.xml2json(responseText);
		if (responseJSON.status == 'success'){
			profileImage.handleScaledImage(responseJSON);
		} else {
			console.error('uploadListener.onUploadCompleteData upload failure...');
		}
	},
	
	'onUploadProgress' : function(obj){
		console.log('onUploadProgress');
		setTimeout( function(){
			console.log(obj.data.bytesLoaded + ' of ' + obj.data.bytesTotal + ' loaded...');
		}, 100);
	},
	
	'onUploadIoError' : function(obj){
		alert('There was a problem uploading your image. Please refresh the page and try again.');
		JQ.unblockUI();
	}
};

// Object Utilities
var objectUtils = {
	'printObject' : function(obj){
		var s = '';
		for (i in obj){
			s += '<strong>'+i+'</strong> -- '+ obj[i] + '<br />';
		}
		return s;
	},
	
	'serialize' : function(json){
		var s = '';
		var first = '';
		for (i in json){
			s += first + i + '=' + json[i];
			first = '&';
		}
		return s;
	}
};

//Controller for Profile Image Upload/Crop/Delete
var profileImage = {
	'image_width' : 140,
	'image_height' : 85,
	'image_left_offset' : 41,
	'image_top_offset' : 159,
	'draggable_width' : null,
	'draggable_height' : null,
	'draggable_left_offset' : null,
	'draggable_top_offset' : null,
	'frame_width' : null,
	'frame_height' : null,
	'frame_left_offset' : null,
	'frame_top_offset' : null,	
	'horizontal_play' : null,
	'vertical_play' : null,
	'tempURL' : null,
	'finalURL' : null,
	'file_extension' : null,
	
	'init': function(){
		var self = this;
		JQ('#uploader_swf_content').hover( function(){
			JQ('#default_image').css({
				'width' : '136px',
				'height' : '81px',
				'border' : '2px solid #f60',
				'cursor' : 'pointer'
			});
		}, function(){
			JQ('#default_image').css({
				'width' : '140px',
				'height' : '85px',
				'border' : 'none'
			});
		});
		JQ('#upload_link').click( function(){
			uploadUtils.browse();
			// uploadUtils.browse() > uploadListener.onUploadFileSelect() > uploadUtils.upload() > uploadListener.onUploadCompleteData()
		});
		JQ('#save_link').click(function(){
			self.postToCropURL(self.getPostData());
		});
		
		JQ('#delete_link').click(function(){
			self.deleteImage();
		});
	},
	
	'handleScaledImage' : function(data){
		//JQ('#status_indicator').html(objectUtils.printObject(data));
		var self = this;
		// http://tinyurl.com/mathIsAwesome
		self.draggable_width = parseInt(data.imgwidth);
		self.draggable_height = parseInt(data.imgheight);
		self.horizontal_play = (self.draggable_width - self.image_width);
		self.vertical_play = (self.draggable_height - self.image_height);
		self.frame_width = self.draggable_width + self.horizontal_play;
		self.frame_height = self.draggable_height + self.vertical_play;
		self.frame_left_offset = self.image_left_offset - self.horizontal_play;
		self.frame_top_offset = self.image_top_offset - self.vertical_play;
		self.draggable_left_offset = Math.round(self.horizontal_play/2);
		self.draggable_top_offset = Math.round(self.vertical_play/2);
		self.tempURL = UPM.TEMP_IMAGE_FOLDER_URL + data.response;
		self.file_extension = "jpg";
		JQ.unblockUI();
		JQ('#uploader_swf_content').css({zIndex:-1});
		self.makeDraggable();
	},
	
	'makeDraggable' : function(){
		var self = this;
		JQ('#default_image, #new_image').hide();
		var previousHTML = JQ('#save_link').html();
		JQ('#draggable_frame').css({
			width: self.frame_width + 'px',
			height: self.frame_height + 'px',
			left: self.frame_left_offset + 'px',
			top: self.frame_top_offset + 'px'
		});
		JQ('#draggable').css({
			backgroundImage:'url('+self.tempURL+')',
			width: self.draggable_width + 'px',
			height: self.draggable_height + 'px',
			left: self.draggable_left_offset + 'px',
			top: self.draggable_top_offset + 'px'
		}).show().draggable({
			zIndex: 1000,
			opacity: 0.8,
			containment : 'parent',
			start: function(){ JQ(this).css({'cursor':'url(/nikeos/site/profile/global/images/cursors/grab.gif), move'}); },
			stop: function(){ JQ(this).css({'cursor': 'pointer'}); }
		}).hover(function(){
				console.log('display tooltip "click to drag"');
				JQ('#save_link').css({'color': '#f60'}).html('CLICK TO DRAG');
			}, function(){
				console.log('hide tooltip "click to drag"');
				JQ('#save_link').css({'color': '#C4C1BE'}).html(previousHTML);
		});
		JQ('#save_link').show();
		JQ('#delete_link, #upload_link').hide();
	},

	'getPostData' : function(){
		var self = this;
		var frame_x = parseInt(JQ('#draggable_frame').css('left').split('px')[0]);
		var frame_y = parseInt(JQ('#draggable_frame').css('top').split('px')[0]);
		var draggable_x = parseInt(JQ('#draggable').css('left').split('px')[0]);
		var draggable_y = parseInt(JQ('#draggable').css('top').split('px')[0]);
		var x = self.image_left_offset - frame_x - draggable_x;
		var y = self.image_top_offset - frame_y - draggable_y;
		console.log('frame_x = '+frame_x);
		console.log('frame_y = '+frame_y);
		console.log('draggable_x = '+draggable_x);
		console.log('draggable_y = '+draggable_y);
		return {
			'email' : profileService.profile.email,
			'description' : 'profile_image',
			'name' : 'profile_image',
			'site' : 'nikeprototype',
			'locale' : UPM.locale,
			'filename' : self.tempURL.split('/')[self.tempURL.split('/').length-1],
			'xcoord' : x,
			'ycoord' : y
		}
	},

	'postToCropURL' : function(data,callback){
		var self = this;
		console.log(data);
		var url = UPM.CROP_URL;
		var post = objectUtils.serialize(data);
		url += '&'+post;
		var loadProfileRequest = new swfAjaxRequest(url,'GET',{},function(data){
			var response = JQ.xml2json(data);
			if(response.status == 'success'){
				self.croppedImageURL = response.response;
				JQ('#new_image').css('background-image', 'url(/vc/profile/'+self.croppedImageURL+'_LRG.'+self.file_extension+')').show();
				JQ('#draggable').hide();
				JQ('#delete_link').show();
				JQ('#save_link, #upload_link').hide();
				JQ('#uploader_swf_content').css({zIndex:-1});
				EventBridge.dispatchEvent({type:"onPostToCropURL", data:null});
			} else {
				console.log('crop failed');
			}
			JQ.unblockUI();
		});
		JQ.blockUI();
		loadProfileRequest.sendRequest();
	},
	
	'deleteImage' : function(){
		console.info('attempting to delete image');
		console.info('TODO: change "confirm" to modal');
		var url = UPM.DELETE_URL;
		if (confirm('Are you sure?')){
			var deleteImageRequest = new swfAjaxRequest(url,'GET',{},function(data){
				var response = JQ.xml2json(data);
				if(response.status == 'success'){
					self.newImageURL = null;
					JQ('#upload_link').show();
					JQ('#delete_link, #save_link').hide();
					JQ('#draggable, #new_image').hide();
					JQ('#default_image').show();
					JQ('#uploader_swf_content').css({zIndex:9999});
					EventBridge.dispatchEvent({type:"onPostToCropURL", data:null});
				} else {
					console.log('didn\'t delete image');
				}
				JQ.unblockUI();
			});
			JQ.blockUI();
			deleteImageRequest.sendRequest();
		}
	}	
}



function getDimensions(ele){
    return { height : ele.height(),
        width: ele.width()
    }
    
}

