/*
Copyright (c) 2009 Ronnie Garcia, Travis Nickels

This file is part of Uploadify v1.6.2

Permission is hereby granted, free of charge, to any person obtaining a copy
of Uploadify and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

UPLOADIFY IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


modification
    date    :   Apr 7, 2009
    author  :   Kenneth Ri
*/

// maximum file numbers for uploading
//set up above    
var maxUploadFiles = 1;
// folder for saving uploaded files.
var folderForSaving = '../../uploads';

// uploading script path
var serverScriptFile = 'UploadPlugIn/upload.php';

// file types that you can upload.
var fileTypes = '*.jpg;*.jpeg;*.gif;*.bmp;*.psd;*.png;*.tif;*.tiff;*.eps;';

// The text that will appear in the file type drop down at the bottom of the browse dialog box
var fileDescription = 'Image files';

// acceptable file sizes in bytes for each image type(type, min_size, max_size)
// file types that isn't contained in this array, isn't limited.

//15728640 ==15 mb
//10 mb 10485760

var typeSize01 = new Array(".jpg",     1048576,       15728640);
var typeSize02 = new Array(".jpeg",    1048576,       15728640);
var typeSize03 = new Array(".gif",	   1048576,       15728640);
var typeSize04 = new Array(".bmp",     8388608,       15728640);
var typeSize05 = new Array(".psd",     8388608,       15728640);
var typeSize06 = new Array(".png",     8388608,       15728640);
var typeSize07 = new Array(".tif",     8388608,       26214400);
var typeSize08 = new Array(".tiff",    8388608,       26214400);
var typeSize09 = new Array(".eps",     8388608,       15728640);
var accFileSizes = new Array(typeSize01, typeSize02, typeSize03, typeSize04, typeSize05, typeSize06, typeSize07, typeSize08, typeSize09);

// orderId range
var minOrderId = 1000;
var maxOrderId = 9999;



/* ****************************************************************************************************   UPLOADER */
function hideUploader()
{
	//alert('here');
	fileUploaded=true;
	$("#yourInputUploader").hide();
	$("#yourInputFileName").show();
}

var totalUploadedFiles=0;
function onCompleteFunc(event, queueID, fileObj, response, data)
{
  //alert('Original name : ' + fileObj.name + '\n\rNew file on server : ' + fileObj.filePath + '\n\rStatus : OK!');
  	totalUploadedFiles=totalUploadedFiles+1;
	
	if(totalUploadedFiles==maxUploadFiles)
	{
		fileUploaded=true;
		$("#id_6_48_error").hide(); 
		$("#id_8_error").hide();
		$('#widg_wizard_success').text('Thank you. Your file ('+ fileObj.name+') has been uploaded successfully. Please enter your photographer\'s name and click next. ');
		$('#widg_wizard_success').dialog("open");
		//hide the uploader
		$("#yourInputUploader").hide();
	
		if(document.forms.cart_quantity.uploadedFileName.value!="")
		{
			document.forms.cart_quantity.uploadedFileName.value=document.forms.cart_quantity.uploadedFileName.value+", "+fileObj.name;
			document.forms.cart_quantity['id[txt_7]'].value=document.forms.cart_quantity['id[txt_7]'].value+", "+currentOrderId+"_"+fileObj.name;
		}
		else
		{
			document.forms.cart_quantity.uploadedFileName.value=fileObj.name;
			
			document.forms.cart_quantity['id[txt_7]'].value=currentOrderId+"_"+fileObj.name;
		}
		
		$("#yourInputFileName").text('Your Uploaded File(s): '+document.forms.cart_quantity.uploadedFileName.value);
		//show the filename
		$("#yourInputFileName").show();
	}
	else if((totalUploadedFiles < maxUploadFiles)&&(maxUploadFiles!=1))
	{//this is an incremental upload
		
		if(document.forms.cart_quantity.uploadedFileName.value!="")
		{
			document.forms.cart_quantity.uploadedFileName.value=document.forms.cart_quantity.uploadedFileName.value+", "+fileObj.name;
			document.forms.cart_quantity['id[txt_7]'].value=document.forms.cart_quantity['id[txt_7]'].value+", "+currentOrderId+"_"+fileObj.name;
		}
		else
		{
			document.forms.cart_quantity.uploadedFileName.value=fileObj.name;
			document.forms.cart_quantity['id[txt_7]'].value=currentOrderId+"_"+fileObj.name;
		}
		
		
		$("#yourInputFileName").text('Your Uploaded File(s): '+document.forms.cart_quantity.uploadedFileName.value);
		//show the filename
		$("#yourInputFileName").show();
		$('#widg_wizard_success').text('Thank you. Your file ('+ fileObj.name+') has been uploaded successfully. You may upload up to: '+maxUploadFiles+' images. ');	
		$('#widg_wizard_success').dialog("open");
	}
	else
	{
		
	}
	
}

// calculates the number of files in queue for uploading
function getFileNumInQueue(id)
{
  var queueCount = 0;

  // counts queue files for uploading
  $('#' + id + 'Queue').children("div.fileUploadQueueItem").each( function() {
    if ( this.style.display != 'none')
    {
      queueCount++;
    }
  });

  return queueCount;
}

// check and start uploading
var currentOrderId="0";

function getOrderId()
{
	var nOrderId = Math.floor(Math.random() * (maxOrderId - minOrderId + 1) + minOrderId);
	nOrderId=nOrderId+"";
	currentOrderId=nOrderId;
	return nOrderId;
}
function nowUploadFiles(id)
{
  // check the number of filies whether is or isn't allowable.
  if (getFileNumInQueue(id) <= maxUploadFiles)
  {
    // generate orderId randomly
    var nOrderId = Math.floor(Math.random() * (maxOrderId - minOrderId + 1) + minOrderId);
	orderIDCall=nOrderId+"";
    $('#' + id).fileUploadSettings('test123', 'food');
    $('#' + id).fileUploadStart();
  }
  else
  {
    //alert('You can upload up to ' + maxUploadFiles + ' file(s).');
	$('#widg_wizard_error_errorMessage').text('You can upload up to ' + maxUploadFiles + ' file(s).');
						$('#widg_wizard_error_error').show();
						$('#widg_wizard_error').dialog("open");
	
  }
}

// function that triggers error while uploading
function onErrorFunc(event, queueID, fileObj, errorObj)
{
  if (errorObj.type == 'HTTP')
  {
    //alert(errorObj.type + ' error.\r\n' + 'Can not upload ' + fileObj.name + '\r\n' + errorObj.status);
	$('#widg_wizard_error_errorMessage').text(errorObj.type + ' error.\r\n' + 'Can not upload ' + fileObj.name + '\r\n' + errorObj.status);
						$('#widg_wizard_error_error').show();
						$('#widg_wizard_error').dialog("open");
  }
  else
  {
    //alert(errorObj.type + ' error.\r\n' + 'Can not upload ' + fileObj.name + '\r\n' + errorObj.text);
	$('#widg_wizard_error_errorMessage').text(errorObj.type + ' error.\r\n' + 'Can not upload ' + fileObj.name + '\r\n' + errorObj.text);
						$('#widg_wizard_error_error').show();
						$('#widg_wizard_error').dialog("open");
  }
}

var flashVer = -1;
if (navigator.plugins != null && navigator.plugins.length > 0) {
	if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
		var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
		var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
		var descArray = flashDescription.split(" ");
		var tempArrayMajor = descArray[2].split(".");
		var versionMajor = tempArrayMajor[0];
		var versionMinor = tempArrayMajor[1];
		var versionRevision = descArray[3];
		if (versionRevision == "") {
			versionRevision = descArray[4];
		}
		if (versionRevision[0] == "d") {
			versionRevision = versionRevision.substring(1);
		} else if (versionRevision[0] == "r") {
			ersionRevision = versionRevision.substring(1);
			if (versionRevision.indexOf("d") > 0) {
				versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
			}
		}
		var flashVer = versionMajor + "." + versionMinor	 + "." + versionRevision;
	}
} else if ( $.browser.msie ) {
	var version;
	var axo;
	var e;
	try {
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}
	flashVer = version.replace("WIN ","").replace(",",".");
}
flashVer = flashVer.split(".")[0];

if(jQuery)(
	function($){
		$.extend($.fn,{
			fileUpload:function(options) {
				if (flashVer >= 9) {
					$(this).each(function(){
						settings = $.extend({
						uploader:      'uploader.swf',
						script:        'uploader.php',
						folder:        '',
						height:        30,
						width:         110,
						cancelImg:     'cancel.png',
						wmode:         'opaque',
						scriptAccess:  'sameDomain',
						fileDataName:  'Filedata',
						displayData:   'percentage',
						onInit:        function() {},
						onSelect:      function() {},
						onCheck:       function() {},
						onCancel:      function() {},
						onError:       function() {},
						onProgress:    function() {},
						onComplete:    function() {}
					}, options);
					var pagePath = location.pathname;
					pagePath = pagePath.split('/');
					pagePath.pop();
					pagePath = pagePath.join('/') + '/';
					var data = '&pagepath=' + pagePath;
					if (settings.buttonImg) data += '&buttonImg=' + escape(settings.buttonImg);
					if (settings.buttonText) data += '&buttonText=' + escape(settings.buttonText);
					if (settings.rollover) data += '&rollover=true';
					data += '&script=' + settings.script;
					data += '&folder=' + escape(settings.folder);
					if (settings.scriptData) {
						var scriptDataString = '';
						for (var name in settings.scriptData) {
							scriptDataString += '&' + name + '=' + settings.scriptData[name];
						}
						data += '&scriptData=' + escape(scriptDataString);
					}
					data += '&btnWidth=' + settings.width;
					data += '&btnHeight=' + settings.height;
					data += '&wmode=' + settings.wmode;
					if (settings.hideButton) data += '&hideButton=true';
					if (settings.fileDesc) data += '&fileDesc=' + settings.fileDesc + '&fileExt=' + settings.fileExt;
					if (settings.multi) data += '&multi=true';
					if (settings.auto) data += '&auto=true';
					if (settings.sizeLimit) data += '&sizeLimit=' + settings.sizeLimit;
					if (settings.simUploadLimit) data += '&simUploadLimit=' + settings.simUploadLimit;
					if (settings.checkScript) data += '&checkScript=' + settings.checkScript;
					if (settings.fileDataName) data += '&fileDataName=' + settings.fileDataName;
					if ($.browser.msie) {
						flashElement = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' + settings.width + '" height="' + settings.height + '" id="' + $(this).attr("id")  + 'Uploader" class="fileUploaderBtn">\
						<param name="movie" value="' + settings.uploader + '?fileUploadID=' + $(this).attr("id") + data + '" />\
						<param name="quality" value="high" />\
						<param name="wmode" value="' + settings.wmode + '" />\
						<param name="allowScriptAccess" value="' + settings.scriptAccess + '">\
						<param name="swfversion" value="9.0.0.0" />\
						</object>';
					} else {
						flashElement = '<embed src="' + settings.uploader + '?fileUploadID=' + $(this).attr("id") + data + '" quality="high" width="' + settings.width + '" height="' + settings.height + '" id="' + $(this).attr("id") + 'Uploader" class="fileUploaderBtn" name="' + $(this).attr("id") + 'Uploader" allowScriptAccess="' + settings.scriptAccess + '" wmode="' + settings.wmode + '" type="application/x-shockwave-flash" />';
					}
					if (settings.onInit() !== false) {
						$(this).css('display','none');
						if ($.browser.msie) {
							$(this).after('<div id="' + $(this).attr("id")  + 'Uploader"></div>');
							document.getElementById($(this).attr("id")  + 'Uploader').outerHTML = flashElement;
						} else {
							$(this).after(flashElement);
						}
						$("#" + $(this).attr('id') + "Uploader").after('<div id="' + $(this).attr('id') + 'Queue" class="fileUploadQueue"></div>');
					}
					$(this).bind("rfuSelect", {'action': settings.onSelect}, function(event, queueID, fileObj) {
						if (event.data.action(event, queueID, fileObj) !== false) {
							var byteSize = Math.round(fileObj.size / 1024 * 100) * .01;
							var suffix = 'KB';
							if (byteSize > 1000) {
								byteSize = Math.round(byteSize *.001 * 100) * .01;
								suffix = 'MB';
							}
							var sizeParts = byteSize.toString().split('.');
							if (sizeParts.length > 1) {
								byteSize = sizeParts[0] + '.' + sizeParts[1].substr(0,2);
							} else {
								byteSize = sizeParts[0];
							}
							if (fileObj.name.length > 20) {
								fileName = fileObj.name.substr(0,20) + '...';
							} else {
								fileName = fileObj.name;
							}

              // --------------------------------------------------------------------------------------------------------------------------------------------------------------
              // if the type of selected file is allowable
              if (getFileNumInQueue($(this).attr('id')) >= maxUploadFiles)
              {
                document.getElementById($(this).attr('id') + 'Uploader').cancelFileUpload(queueID);
               	$('#widg_wizard_error_errorMessage').text('You can upload up to ' + maxUploadFiles + ' file(s). Only the first image will be uploaded.');
				$('#widg_wizard_error_error').show();
                $('#widg_wizard_error').dialog("open");
				
				//$('#widg_wizard_error_errorMessage').text('You can upload up to ' + maxUploadFiles + ' file(s). Only the first image will be uploaded.');
				 //alert('failed : ' + fileObj.name + '.\n\rYou can upload up to ' + maxUploadFiles + ' file(s).\n\rYou should remove one or more files in queue for this file.');
				return;
              }
              var extFp = fileObj.name.split(".");
              var fType = "." + extFp[extFp.length - 1];
              if (fileTypes.indexOf(fType.toLowerCase()) != -1)
              {
                // iterates all the file types that is allowable
                for (var iType = 0; iType < accFileSizes.length; iType++)
                {
                  // if the size of selected file is smaller than the minimun size of that filetype.
                  if (fType.toLowerCase() == accFileSizes[iType][0])
                  {
                    if (fileObj.size < accFileSizes[iType][1])
                    {
                      // cancel this file
                      document.getElementById($(this).attr('id') + 'Uploader').cancelFileUpload(queueID);
                     //alert('The size of ' + fileObj.name + ' is too small.');					  
					  $('#widg_wizard_error').dialog("open");
					  $('#widg_wizard_error_errorMessage').text('The file you are uploading appears to be too small. Use of a low resolution file will result in qualitative issues and your prints will look soft and pixilated. Please click "CLOSE" to back up and select a new file. If you have any questions please feel free to contact us at: info@reproductions.com or 646.502.3700 (during our business hours M-F 9am - 6pm est).');
						$('#widg_wizard_error_error').show();
						//alert('here');
						
                      return;
                    }
                    else if (fileObj.size > accFileSizes[iType][2])
                    {
                      // cancel this file
                      document.getElementById($(this).attr('id') + 'Uploader').cancelFileUpload(queueID);
                      //alert('The size of ' + fileObj.name + ' is too large.');
					  $('#widg_wizard_error_errorMessage').text('The file you are uploading appears to be too big. Please click "CLOSE" to back up and select a new file. If you have any questions please feel free to contact us at: info@reproductions.com or 646.502.3700 (during our business hours M-F 9am - 6pm est).');
						$('#widg_wizard_error_error').show();
						$('#widg_wizard_error').dialog("open");
                      return;
                    }
                  }
                }
                // add selected file to the queue for uploading
                $('#' + $(this).attr('id') + 'Queue').append('<div id="' + $(this).attr('id') + queueID + '" class="fileUploadQueueItem">\
                    <div class="cancel">\
                      <a href="javascript:$(\'#' + $(this).attr('id') + '\').fileUploadCancel(\'' + queueID + '\')"><img src="' + settings.cancelImg + '" border="0" /></a>\
                    </div>\
                    <span class="fileName">' + fileName + ' (' + byteSize + suffix + ')</span><span class="percentage">&nbsp;</span>\
                    <div class="fileUploadProgress" style="width: 100%;">\
                      <div id="' + $(this).attr('id') + queueID + 'ProgressBar" class="fileUploadProgressBar" style="width: 1px; height: 3px; overflow: hidden;"></div>\
                    </div>\
                  </div>');
              }
              else
              {
                document.getElementById($(this).attr('id') + 'Uploader').cancelFileUpload(queueID);
                //alert(fileObj.name + ' : Invalid file type.');
				$('#widg_wizard_error_errorMessage').text(fileObj.name + ' : Invalid file type.');
						$('#widg_wizard_error_error').show();
						$('#widg_wizard_error').dialog("open");
				
              }
              // --------------------------------------------------------------------------------------------------------------------------------------------------------------
						}
					});
					if (typeof(settings.onSelectOnce) == 'function') {
						$(this).bind("rfuSelectOnce", settings.onSelectOnce);
					}
					$(this).bind("rfuCheckExist", {'action': settings.onCheck}, function(event, checkScript, fileQueue, folder, single) {
						var postData = new Object();
						postData.folder = pagePath + folder;
						for (var queueID in fileQueue) {
							postData[queueID] = fileQueue[queueID];
							if (single) {
								var singleFileID = queueID;
							}
						}
						$.post(checkScript, postData, function(data) {
							for(var key in data) {
								if (event.data.action(event, checkScript, fileQueue, folder, single) !== false) {
									var replaceFile = confirm('Do you want to replace the file \'' + data[key] + '\'?');
									if (!replaceFile) {
										document.getElementById($(event.target).attr('id') + 'Uploader').cancelFileUpload(key);
									}
								}
							}
							if (single) {
								document.getElementById($(event.target).attr('id') + 'Uploader').startFileUpload(singleFileID, true);
							} else {
								document.getElementById($(event.target).attr('id') + 'Uploader').startFileUpload(null, true);
							}
						}, "json");
					});
					$(this).bind("rfuCancel", {'action': settings.onCancel}, function(event, queueID, fileObj, data) {
						if (event.data.action(event, queueID, fileObj, data) !== false) {
							$("#" + $(this).attr('id') + queueID).fadeOut(250, function() { $("#" + $(this).attr('id') + queueID).remove()});
						}
					});
					$(this).bind("rfuClearQueue", {'action': settings.onClearQueue}, function() {
						if (event.data.action() !== false) {
							$('#' + $(this).attr('id') + 'Queue').contents().fadeOut(250, function() {$('#' + $(this).attr('id') + 'Queue').empty()});
						}
					});
					$(this).bind("rfuError", {'action': settings.onError}, function(event, queueID, fileObj, errorObj) {
						if (event.data.action(event, queueID, fileObj, errorObj) !== false) {
							$("#" + $(this).attr('id') + queueID + " .fileName").text(errorObj.type + " Error - " + fileObj.name);
							$("#" + $(this).attr('id') + queueID).css({'border': '3px solid #FBCBBC', 'background-color': '#FDE5DD'});
						}
					});
					$(this).bind("rfuProgress", {'action': settings.onProgress, 'toDisplay': settings.displayData}, function(event, queueID, fileObj, data) {
						if (event.data.action(event, queueID, fileObj, data) !== false) {
							$("#" + $(this).attr('id') + queueID + "ProgressBar").css('width', data.percentage + '%');
							if (event.data.toDisplay == 'percentage') displayData = ' - ' + data.percentage + '%';
							if (event.data.toDisplay == 'speed') displayData = ' - ' + data.speed + 'KB/s';
							if (event.data.toDisplay == null) displayData = ' ';
							$("#" + $(this).attr('id') + queueID + " .percentage").text(displayData);
						}
					});
					$(this).bind("rfuComplete", {'action': settings.onComplete}, function(event, queueID, fileObj, response, data) {
						if (event.data.action(event, queueID, fileObj, unescape(response), data) !== false) {
							$("#" + $(this).attr('id') + queueID).fadeOut(250, function() { $("#" + $(this).attr('id') + queueID).remove()});
							$("#" + $(this).attr('id') + queueID + " .percentage").text(' - Completed');
						}
					});
					if (typeof(settings.onAllComplete) == 'function') {
						$(this).bind("rfuAllComplete", settings.onAllComplete);
					}
				});
			}
		},
		fileUploadSettings:function(settingName, settingValue) {
			$(this).each(function() {
								  
				document.getElementById($(this).attr('id') + 'Uploader').updateSettings(settingName,settingValue);
			});
		},
		fileUploadStart:function(queueID) {
			$(this).each(function() {
				document.getElementById($(this).attr('id') + 'Uploader').startFileUpload(queueID, false);
			});
		},
		fileUploadCancel:function(queueID) {
			$(this).each(function() {
				document.getElementById($(this).attr('id') + 'Uploader').cancelFileUpload(queueID);
			});
		},
		fileUploadClearQueue:function() {
			$(this).each(function() {
				document.getElementById($(this).attr('id') + 'Uploader').clearFileUploadQueue();
			});
		}
	})
})(jQuery);