 function calcHeight()
 {
	 //find the height of the internal page
	 var the_height=
	 document.getElementById('the_iframe').contentWindow.
	 document.body.scrollHeight;

	 //change the height of the iframe
	 document.getElementById('the_iframe').height=
	 the_height;
 }

// 會員功能選單開闔控制
function showMemberDropMenu(){
  var status = $('.member_dropmenu').css('display');
  if(status == 'none')
    $('.member_dropmenu').slideDown(500);
  else
    $('.member_dropmenu').slideUp(100);
}

// 網站功能選單開闔控制
function showTopSubMobileDropMenu(){
  console.log('enter showTopSubMobileDropMenu');
  var status = $('.topsubmenuMobile').css('display');
  if(status == 'none')
    $('.topsubmenuMobile').slideDown(500);
  else
    $('.topsubmenuMobile').slideUp(100);
}

// 語系切換功能選單開闔控制
function showLanguageDropMenu(){
  var status = $('.language_dropmenu').css('display');
  if(status == 'none')
    $('.language_dropmenu').slideDown("slow");
  else
    $('.language_dropmenu').slideUp(100);

}

// 開啟左側功能列子選單
function openNav(num){
  $(".header").removeClass("active_1");
  $(".navtitle_"+num).addClass("active_1");

  var isHidden = $(".nav_"+num).is(":hidden");
  $(".subcat").hide();

  if(num >= 1 && num < 12 && isHidden)
    $(".nav_"+num).show();
  else{
    $(".navtitle_"+num).removeClass("active_1");
    $(".nav_"+num).hide();
  }
}

function genHtmlcode(){
  var str = "";

  var bannerimg = $('input[name=banner]:checked').val();
  var salepage = $('input[name=salepage]:checked').val();

//  var domainpath = "pages/images/";
  var domainpath = "";
  var bannerpath = domainpath + bannerimg;

  str = '<a href="'+salepage+'" target="_blank"><img src="'+bannerpath+'" border="0"></a>';

  $("#promote_htmlcode").val('');
  $("#promote_htmlcode").val(str);
}

function chgRightContent(blockname,num){
  $('.header').removeClass("active_1");
  $('.navtitle_'+num).addClass("active_1");
  $('.contentBlock').hide();
  $('#'+blockname).show();
}

function showModal(bannerName){
//  var bannerurl = 'pages/images/' + bannerName;
 var bannerurl = bannerName;
  $("#bannerImgModal_src").attr('src',bannerurl);
  $('#bannerImgModal').foundation('reveal', 'open');
}

function registerSuccess(){
  /*
   *依照 alert msg 類別呼叫對應function
   *成功訊息 : showSuccessMessage()
   *錯誤訊息 : showErrorMessage()
   *提示訊息 : showNotifyMessage()
   */
    showSuccessMessage('註冊成功!!註冊成功!!註冊成功!!註冊成功!!');
}



function replaceDraft(){
  var draft = $('#replydraft').val();

  if(draft != -1){
    $('#replyContent').val('');
    $('#replyContent').val(draft);
  }
}

function setPdtName(pdtname){
  $('#pdtName').val(pdtname);
}

function setIdxHotPdtName(pdtname){
  $('#idxHotPdtName').val(pdtname);
}

function setIdxFreePdtName(pdtname){
  $('#idxFreePdtName').val(pdtname);
}

function setListPdtName(pdtname){
  $('#listPdtName').val(pdtname);
}

/*下拉選單收回 - 相關function Start-----------------------------------*/
function addEvent( obj, type, fn ) {
  if ( obj.attachEvent ) {
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
    obj.attachEvent( 'on'+type, obj[type+fn] );
  } else
    obj.addEventListener( type, fn, false );
}
function selectBack(e) {
  var clickElement = "good";
  e = window.event || e;
  if (e.srcElement != null){
    clickElement = e.srcElement.id;
  } else {
    clickElement = e.target.id;
  }

  // 商品下拉選單
  if($('#recommendPdtDropList').css('display') == 'block'){
    if (clickElement != "pdtName" && clickElement != "good") {
      document.getElementById("recommendPdtDropList").style.display = "none";
    }
  }
  if($('#pdtDropList').css('display') == 'block'){
    if (clickElement != "pdtName" && clickElement != "good") {
      document.getElementById("pdtDropList").style.display = "none";
    }
  }
  if($('#freePdtDropList').css('display') == 'block'){
    if (clickElement != "pdtName" && clickElement != "good") {
      document.getElementById("freePdtDropList").style.display = "none";
    }
  }

  // 語系下拉選單
  if (clickElement == "langIcon"){
  }else
    $('.language_dropmenu').slideUp(100);

  // 登入會員下拉選單
  if (clickElement == "memberIcon"){
  }else
    $('.member_dropmenu').slideUp(100);

  // 網站功能選單
  if(clickElement == "functionMenuIcon"){
  }else
    $('.topsubmenuMobile').slideUp(100);
}
/*下拉選單收回 - 相關function End-----------------------------------*/

// initCKEditor
function initCKEditor (targetfileid, config) {
  // 設定config
  if(!config){
    config = {
      language : 'zh', // 介面語言，預設為 'en'
      // width: 400, // 寬度，不設定就自動填滿
      height : 200, //高度，這裡不包含Toolbar的高度
      resize_enabled : false,  //是否可以resize
      // 按下Enter為增加一個<br>，
      // 預設為 '<p></p>'，CKEDITOR.ENTER_P=1、CKEDITOR.ENTER_BR=2、CKEDITOR.ENTER_DIV=3
      enterMode : CKEDITOR.ENTER_BR,
      //載入自己設定的css，若沒有則自動載入default的css(/js/ckeditor/contents.css)
      //contentsCss : "/js/ckeditor/contents.css",

      toolbarCanCollapse : false, //toolbar是否可以縮起來
      toolbar : //toolbar的內容
        [
            ['Font','FontSize'],
            ['Bold','Italic','Underline','Strike','-','TextColor','BGColor'],
            ['NumberedList','BulletedList','Blockquote'],
            ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
            ['Undo','Redo'],
            ['Find'],
            ['Link','Unlink'],
            ['testplugin']
        ],
        //額外載入的plugin，
        // 要找到plugin的code寫在哪請從js/ckeditor/plugins找尋相對應名稱的資料夾即可
        //extraPlugins : 'testplugin'
    }
  }

  var editor = CKEDITOR.instances[ targetfileid ];
  // 這個半段式主要是為了防止該區域已經初始化過，若是已經初始化過則沒要再初始化一次
  if(!editor){
    // 初始化的動作，若是在初始化的時候沒有傳入config，則會自動抓取js/ckeditor/config.js裡面的內容
    // 傳入的id為以後辨識用
    return CKEDITOR.replace( document.getElementById( targetfileid ), config );
  }
}



// init ZeroClipboard
var clip = null;
function initZeroClipboard () {
  (function $(id) { return document.getElementById(id); })

  clip = new ZeroClipboard.Client();
  clip.setHandCursor( true );
   clip.addEventListener('complete', function (client, text) {
    alert("已複製!" );
	});

}

function move_swf (ee) {
  copything = document.getElementById(ee.id+"_text").value;
  clip.setText(copything);
/*  clip.addEventListener('complete', function (client, text) {
    alert("已複製!" );
	});
*/
  if (clip.div)
  {
    clip.receiveEvent('mouseout', null);
    clip.reposition(ee.id);
  }
  else{ clip.glue(ee.id);   }

  clip.receiveEvent('mouseover', null);

}

// 初始化選擇日期功能
function initDatePicker () {
  $(".datepicker").datepicker({
      showOn: "both",
	  dateFormat: "yy-mm-dd",
      buttonImage: "pages/images/calendar.gif",
      buttonImageOnly: true
  }).css('width','100px').css('float','left').css('margin-bottom','0');

  $(".ui-datepicker-trigger").css('float','left').css('margin-left','5px').css('margin-top','5px');
  $(".ui-datepicker-trigger").attr('title','');
}

// 計算網頁目前可見區域寬度來定位Modal位移值
function countClientWidth (modalwidth, modalname) {
  var clientwidth = document.body.clientWidth;
  var shiftvalue;
  if(clientwidth > modalwidth){
    shiftvalue = -((modalwidth / clientwidth) * 100) / 2;
    shiftvalue = shiftvalue + "%";
    $("#"+modalname).css('margin-left',shiftvalue);
  }else{
    $("#"+modalname).css('margin-left','-50%');
  }
}

// init忘記密碼視窗內容
function initQueryForm () {
  $("input[name=queryType]").attr("checked",false);
  $("#register-email").hide();
  $("#register-backupemail").hide();
  $("#register-phone").hide();
}

// 依查詢類型顯示相關填寫表格
function showQueryForm () {
  var type = $("input[name=queryType]:checked").val();
  if(type == 1 || type == 2){
    $("#register-email").show();
    $("#register-backupemail").show();
    $("#register-phone").hide();
  }else{
    $("#register-email").show();
    $("#register-backupemail").show();
    $("#register-phone").show();
  }
}




function getData(){
	$(".accountMainContent").mask("查詢中...");

  	var params = {
  		start : indexValue.start,
  		len : indexValue.len,
  		search : indexValue.search,
  		id : indexValue.id,
  		showNotFound : indexValue.showNotFound
   	}
  	if(indexValue.start == 0){
		$('#scrollcontent').empty().hide();
	}
	if ( ! indexValue.showNotFound ) {
		indexValue.showNotFound = "Y";
	}
	indexValue.searching  = true;
	 $.ajaxSetup({ async: false });
  	$.getJSON(indexValue.phpurl,params,function(data){
  		if(data.length != 0){
  			var cont = '';
  			for( var i = 0 ; i < data.length ; i++ ){
					cont += data[i] ;
			}

			$('#scrollcontent').append(cont).fadeIn();
			indexValue.start = indexValue.start + indexValue.len;
			indexValue.searching  = false;
 		} else {
//		 	if(indexValue.start == 0){
//				return 0;
//			}
if(indexValue.start == 0 && 	indexValue.showNotFound == "Y" )
		TINY.box.show({html:"<div style='margin:10px;'>未發現任何資料!</div>",width:160,height:60});
//		TINY.box.show({html:"<div style='margin:10px;'><?=$ln['no_data_found']?></div>",width:160,height:60});
//			$('#scrollcontent').after("<div style='margin:20px;display:none;' id='temp'>以下無任何資料...</div>");
//			$('#temp').fadeIn().fadeOut(5000, function() { $(this).remove(); });
		}
  	});
	$(".accountMainContent").unmask();
}



function deleteData(phpurl,removeElement){

  	$.getJSON(phpurl,function(data){
		if(data['success']==0) {
			$('#scrollcontent').after("<div style='margin:5px;display:none;' id='temp'>" + data['message'] + "</div>");
			$('#temp').fadeIn().fadeOut(5000, function() { $(this).remove(); });
 		} else {
			$("#"+removeElement).remove();
		}
  	});
}


/* upload */

	function roundNumber(num, dec)
	{
		var result = Math.round( Math.round( num * Math.pow( 10, dec + 1 ) ) / Math.pow( 10, 1 ) ) / Math.pow(10,dec);
		return result;
	}
	function updateUploadifySettings(uploader)
	{
		if(typeof(uploader.attr("data"))!="undefined")
		{
			var uploadifySettings = uploader.uploadifySettings("scriptData");
			var customData = eval('({' + uploader.attr("data") + '})');
			var data="";
			for(var name in customData)
			{
				data += "'" + name + "':";
				if(customData[name].substr(0,9)=="selector:")
					data += "'" + $(customData[name].substr(9).toString()).val() + "',";
				else
					data += "'" + customData[name] + "',";
			}
			data = data.substr(0, data.length-1);
			data = eval('({' + data + '})');
			uploader.uploadifySettings("scriptData", $.extend(uploadifySettings, data));
		}
	}
	function preventSubmit(event)
	{
		event.preventDefault();
	}
	function submitForm(event)
	{
		event.preventDefault();
		var self = event.data.uploader;
		updateUploadifySettings(self);
		var queue;
		if(typeof(self.attr("queueId"))!="undefined")
			queue = $("#"+self.attr("queueId"));
		else
			queue = $("#" + self.attr("id") + "Queue");
		if(queue.children().length>0)
		{
			var uploadifySettings = self.uploadifySettings("scriptData");
			var formData = $(this).serializeArray();
			var formDataJSON = {};
			for(var i=0; i<formData.length; i++)
				formDataJSON[formData[i].name] = escape(formData[i].value);
			self.uploadifySettings("scriptData", $.extend(uploadifySettings, formDataJSON));
			if(typeof(self.attr("ajaxLoaderId"))!="undefined")
				$("#"+self.attr("ajaxLoaderId")).css("display", "inline");
			$(this).bind("submit", preventSubmit);
			self.uploadifyUpload();
		}
		else
		{
			if(typeof(self.attr("ajax"))!="undefined" && self.attr("ajax")=="true")
			{
				var data = $(this).serializeArray();
				var url = $(this).attr("action");
				var method = $(this).attr("method");
				var form = $(this);
				if(typeof(self.attr("ajaxLoaderId"))!="undefined")
					$("#"+self.attr("ajaxLoaderId")).css("display", "inline");
				$.ajax({
					url: url,
					data: data,
					type: method,
					async: false,
					success: function(data){
						if(typeof(self.attr("ajaxInfoId"))!="undefined")
						{
							$("#"+self.attr("ajaxInfoId")).html("");
							$("#"+self.attr("ajaxInfoId")).html(data).css("display", "block");
						}
						form[0].reset();
						$("[name='IMUFiles[]']").remove();
						if(typeof(self.attr("queueId"))!="undefined")
							$("#"+self.attr("queueId")).html("");
						else
							$("#" + self.attr("id") + "Queue").html("");
						if(typeof(self.attr("ajaxLoaderId"))!="undefined")
							$("#"+self.attr("ajaxLoaderId")).css("display", "none");
						form.one("submit", {'uploader':self}, submitForm);
					}
				});
			}
			else
				$(this).submit();
		}
	}

function prepareUploadButton(type){
	var myIndex = pdtsalepage_idx;
	var IMU_banner_idx = 0;
	selector = "#" + type + "_"+myIndex;
	if ( type == 'banner' ) {
		if ( banner_idx >= 4 ) {
			IMU_banner_idx = banner_idx;
			selector = "#banner_upload_" + banner_idx;
		} else
			selector = "[id^=banner_upload_]";
	}
//	if ( type != 'lp_file' ) myIndex = type + "1";
	$(selector).each(function(index){
		var self = $(this);
//		if ( type == 'banner' && banner_idx < 4) {
		if ( type == 'banner' ) {
			IMU_banner_idx += 1;
			myIndex = type + IMU_banner_idx;
		}
		self.attr("id", "IMU"+myIndex);
		if(typeof(self.attr("startOn"))!="undefined")
		{
			if(self.attr("startOn")=="manually")
			{
				self.after("<input type='button' value='" + (typeof(self.attr("buttonCaption"))=="undefined" ? '':self.attr("buttonCaption")) + "' id='IMU"+myIndex+"start' class='uploadButton' />");
				$("#IMU"+myIndex+"start").click(function(){
					updateUploadifySettings(self);
					self.uploadifyUpload();
				});
			}
			else if(self.attr("startOn").substr(0, 8)=="onSubmit")
				$("#"+self.attr("startOn").substr(9)).one("submit", {'uploader':self}, submitForm);
		}
		var fileExt = "";
		if(typeof(self.attr("fileExt"))!="undefined")
		{
			var fileExtSplit = self.attr("fileExt").split(",");
			for(var i=0; i<fileExtSplit.length; i++)
			{
				fileExt += "*."+fileExtSplit[i];
				if(i+1<fileExtSplit.length)
					fileExt += ";";
			}
		}
		var buttonImg = "";
		if(typeof(self.attr("button"))!="undefined")
			buttonImg = self.attr("button");
		var bwidth = 120;
		if(typeof(self.attr("bwidth"))!="undefined")
			bwidth = self.attr("bwidth");
		var bheight = 30;
		if(typeof(self.attr("bheight"))!="undefined")
			bheight = self.attr("bheight");
		var buttonText = "SELECT FILES";
		if(typeof(self.attr("buttonText"))!="undefined")
			buttonText = self.attr("buttonText");
		var customQueueId = "";
		if(typeof(self.attr("queueId"))!="undefined")
			customQueueId = self.attr("queueId");
		var maxSize = "";
		if(typeof(self.attr("maxSize"))!="undefined")
			maxSize = self.attr("maxSize");
		var uploadScript = "upload.php";
		if(typeof(self.attr("uploadScript"))!="undefined")
			uploadScript = self.attr("uploadScript");
		var wmode = "transparent";
		if(typeof(self.attr("wmode"))!="undefined")
			wmode = self.attr("wmode");
		var filesLimit = 999;
		if(typeof(self.attr("filesLimit"))!="undefined")
			filesLimit = self.attr("filesLimit");
		var sessionId = "";
		if(typeof(self.attr("sessionId"))!="undefined")
			sessionId = self.attr("sessionId");
		var ajax = "false";
		if(typeof(self.attr("ajax"))!="undefined")
			ajax = self.attr("ajax");
		var method= "post";
		if(typeof(self.attr("method"))!="undefined")
			method = self.attr("method");

		var scriptData = "'action':'upload', 'path':'"+self.attr('path')+"', 'PHPSESSID':'"+sessionId+"'";
		var fileDesc = "";
		if(typeof(self.attr("fileDesc"))!="undefined") {
			fileDesc = self.attr("fileDesc");
		}
		var fileType = "";
		if(typeof(self.attr("fileType"))!="undefined") {
			fileType = self.attr("fileType");
			scriptData += ", 'fileType':'" + self.attr("fileType") + "'";
		}
		if(typeof(self.attr("thumbnails"))!="undefined")
			scriptData += ", 'thumbnails':'" + self.attr("thumbnails") + "'";
		if(typeof(self.attr("thumbnailsFolders"))!="undefined")
			scriptData += ", 'thumbnailsFolders':'" + self.attr("thumbnailsFolders") + "'";
		if(typeof(self.attr("thumbnailsCrop"))!="undefined")
			scriptData += ", 'thumbnailsCrop':'" + self.attr("thumbnailsCrop") + "'";

		if(typeof self.uploadify == 'function')	{
		self.uploadify({
			'uploader'  : 'lib/file_upload/js/upload.swf',
			'script'    : uploadScript,
			'scriptData': eval('({' + scriptData + '})'),
			'queueID'	: customQueueId,
			'cancelImg' : 'lib/file_upload/close.png',
			'displayData' : (self.attr("onprogress")=="speed" ? "speed":"percentage"),
			'fileExt'	: fileExt,
			'fileDesc'	: fileDesc,
			'method'	: method,
			'buttonImg'	: buttonImg,
			'buttonText': buttonText,
			'wmode'		: wmode,
			'width'		: bwidth,
			'height'	: bheight,
			'sizeLimit'	: maxSize,
			'hideButton': (self.attr("hideButton")=="true" ? true:false),
			'auto'      : (self.attr("startOn")=="auto" ? true:false),
			'multi'		: (self.attr("multi")=="true" ? true:false),
			'queueSizeLimit' : filesLimit,
			'onSelect' : function(event, queueId, fileObj){
				if(self.attr("multi")!="true")
					if($("#"+queueId).html()!="")
						if(customQueueId!="")
							$("#"+customQueueId).html("");
						else
							$("#" + self.attr("id") + "Queue").html("");
			},
			'onSelectOnce' : function(event, data){
				if(self.attr("startOn")=="auto")
					updateUploadifySettings(self);
			},
			'onComplete' : function(event, queueId, fileObj, response, data){
				var responseJSON = $.parseJSON(response);
				if(typeof(responseJSON.error)!="undefined")
				{
					$("#" + self.attr("id") + queueId).html(responseJSON.error);
					return false;
				}
				else
				{
					if(self.attr("startOn").substr(0, 8)=="onSubmit")
						$("#"+self.attr("startOn").substr(9)).append("<input type='hidden' name='IMUFiles[]' value='"+responseJSON.filename.replace("'", "%27")+"' />");
					if(self.attr("afterUpload")=="link" || self.attr("afterUpload")=="filename" || self.attr("afterUpload")=="image" || self.attr("afterUpload")=="none")
					{
						$("#" + self.attr("id") + queueId + " .uploadifyProgress").animate({opacity: 0}, 500, function(){$(this).remove();});
						$("#" + self.attr("id") + queueId).html((self.attr("allowRemove")=="true" ? "<div class='cancel'><input class='button_cancel' name='removeFile' filename='"+responseJSON.filename.replace("'", "%27")+"' type='button'></div>":"") + (self.attr("afterUpload")=="link" || self.attr("afterUpload")=="image" ? "<a href='" + responseJSON.path + responseJSON.filename.replace("'", "%27") + "' target='_blank'>":"") + (self.attr("afterUpload")=="image" && (responseJSON.extension.toLowerCase()=="jpg" || responseJSON.extension.toLowerCase()=="jpeg" || responseJSON.extension.toLowerCase()=="bmp" || responseJSON.extension.toLowerCase()=="png" || responseJSON.extension.toLowerCase()=="tiff" || responseJSON.extension.toLowerCase()=="gif")  ? "<img class='uploadedImage' src='" + responseJSON.path + responseJSON.filename.replace("'", "%27") +"' />":(self.attr("afterUpload")!="none" ? "<span class='fileName'>"+fileObj.name+"</span>" : "")) + (self.attr("afterUpload")=="link" || self.attr("afterUpload")=="image" ? "</a>":""));
						if(typeof(self.attr("thumbnailsAfterUpload"))!="undefined")
						{
							var thumbnailsAfterUploadSplit = self.attr("thumbnailsAfterUpload").split(",");
							var thumbnailsFoldersSplit = new Array();
							if(typeof(self.attr("thumbnailsFolders"))!="undefined")
								thumbnailsFoldersSplit= self.attr("thumbnailsFolders").split(",");
							for(var i=0; i<thumbnailsAfterUploadSplit.length; i++)
							{
								display = $.trim(thumbnailsAfterUploadSplit[i]);
								folder = ($.trim(thumbnailsFoldersSplit[i])=="" ? self.attr("path") : $.trim(thumbnailsFoldersSplit[i]));
								if(display!="filename" && display!="image" && display!="link")
									$("#" + self.attr("id") + queueId).append("<span class='afterUploadThumbnail'>" + display + "</span>");
								else
									$("#" + self.attr("id") + queueId).append("<span class='afterUploadThumbnail'>" + (display=="link" || display=="image" ? "<a href='" + folder + responseJSON.thumbnails[i].replace("'", "%27") + "' target='_blank'>":"") + (display=="image" && (responseJSON.extension.toLowerCase()=="jpg" || responseJSON.extension.toLowerCase()=="jpeg" || responseJSON.extension.toLowerCase()=="bmp" || responseJSON.extension.toLowerCase()=="png" || responseJSON.extension.toLowerCase()=="tiff" || responseJSON.extension.toLowerCase()=="gif")  ? "<img class='uploadedThumbnail' src='" + folder + responseJSON.thumbnails[i].replace("'", "%27") + "' />":"<span class='fileName'>" + "thumb" + i + "_" + fileObj.name + "</span>") + (display=="link" || display=="image" ? "</a>":"") + "</span>");
							}
						}
						return false;
					}
				}
			},
			'onAllComplete' : function(event, data){
				if(typeof(self.attr("afterUpload"))!="undefined" && self.attr("afterUpload")!="link" && self.attr("afterUpload")!="filename" && self.attr("afterUpload")!="image" && self.attr("afterUpload")!="none")
				{
					var message = self.attr("afterUpload");
					message = message.replace("IMUfilesUploaded", data.filesUploaded);
					message = message.replace("IMUerrors", data.errors);
					message = message.replace("IMUtotalSizeB", data.allBytesLoaded);
					message = message.replace("IMUtotalSizeKB", roundNumber(data.allBytesLoaded/1024, 2));
					message = message.replace("IMUtotalSizeMB", roundNumber(data.allBytesLoaded/1024/1024, 2));
					message = message.replace("IMUtotalSizeGB", roundNumber(data.allBytesLoaded/1024/1024/1024, 2));
					message = message.replace("IMUspeedB", roundNumber(Math.round(data.speed*1024), 2));
					message = message.replace("IMUspeedKB", roundNumber(Math.round(data.speed), 2));
					message = message.replace("IMUspeedMB", roundNumber(Math.round(data.speed/1024), 2));
					message = message.replace("IMUspeedGB", roundNumber(Math.round(data.speed/1024/1024), 2));
					$("#" + self.attr("id") + "Queue").html(message);
				}
				if(self.attr("startOn").substr(0, 8)=="onSubmit")
				{
					var form = $("#"+self.attr("startOn").substr(9));
					form.unbind("submit", preventSubmit);
					if(ajax=="true")
					{
						var data = form.serializeArray();
						var url = form.attr("action");
						var method = form.attr("method");
						if(typeof(self.attr("ajaxLoaderId"))!="undefined")
							$("#"+self.attr("ajaxLoaderId")).css("display", "inline");
						$.ajax({
							url: url,
							data: data,
							type: method,
							async: false,
							success: function(data){
								if(typeof(self.attr("ajaxInfoId"))!="undefined")
								{
									$("#"+self.attr("ajaxInfoId")).html("");
									$("#"+self.attr("ajaxInfoId")).html(data).css("display", "block");
								}
								form[0].reset();
								$("[name='IMUFiles[]']").remove();
								if(typeof(self.attr("queueId"))!="undefined")
									$("#"+self.attr("queueId")).html("");
								else
									$("#" + self.attr("id") + "Queue").html("");
								if(typeof(self.attr("ajaxLoaderId"))!="undefined")
									$("#"+self.attr("ajaxLoaderId")).css("display", "none");
								form.one("submit", {'uploader':self}, submitForm);
							}
						});
					}
					else
						form.submit();
				}
			},
			'onError': function (event, queueID ,fileObj, errorObj) {
				/* if you got some problems just uncomment this code for debugging */
				/*var msg;
				if (errorObj.info == 404)
				   msg = 'Could not find upload script.';
				else if(errorObj.type === "HTTP")
				   msg = errorObj.type+ ": " +errorObj.info;
				else if(errorObj.type ==="File Size")
				   msg = fileObj.name+ ": " +errorObj.type;
				else
				   msg = errorObj.type+ ": " +errorObj.info;
				alert(msg);
				return false;*/
            }
		});
		}

		if(typeof(self.attr("allowRemove"))!="undefined") {

		if(self.attr("allowRemove")=="true")
		{
			$("#"+(customQueueId!="" ? customQueueId:self.attr("id")+"Queue")+" [name=removeFile]").on("click", function(){
				var selfRemove = $(this);
				if(typeof(self.attr("removeData"))!="undefined")
				{
					var customRemoveData = eval('({' + self.attr("removeData") + '})');
					var data="";
					for(var name in customRemoveData)
					{
						data += "'" + name + "':";
						if(customRemoveData[name].substr(0,9)=="selector:")
							data += "'" + $(customRemoveData[name].substr(9).toString()).val() + "',";
						else
							data += "'" + customRemoveData[name] + "',";
					}
					data = data.substr(0, data.length-1);
					data = eval('({' + data + '})');
				}
				$.ajax({
							url: uploadScript,
							data: "action=remove&filename="+selfRemove.attr("fileName")+(typeof(data)!="undefined" ? "&"+$.param(data) : ""),
							type: "POST",
							async: false,
							success: function(data){
									if(data!="")
										alert(data);
									else
										selfRemove.parent().parent().animate({opacity: 0}, 500, function(){$(this).remove();});
							}
					});
			});
		}
	}

	});

}


// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {

	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}

function setSelectedIndex(s, v) {
	for ( var i = 0; i < s.options.length; i++ ) {
		if ( s.options[i].value == v ) {
			s.options[i].selected = true;
			return;
		}
	}
}


function prepareSingleUploadButton(type){
	selector = "#" + type ;
	$(selector).each(function(index){
		var self = $(this);
		self.attr("id", "IMU"+type);
		if(typeof(self.attr("startOn"))!="undefined")
		{
			if(self.attr("startOn")=="manually")
			{
				self.after("<input type='button' value='" + (typeof(self.attr("buttonCaption"))=="undefined" ? '':self.attr("buttonCaption")) + "' id='IMU"+myIndex+"start' class='uploadButton' />");
				$("#IMU"+type).click(function(){
					updateUploadifySettings(self);
					self.uploadifyUpload();
				});
			}
			else if(self.attr("startOn").substr(0, 8)=="onSubmit")
				$("#"+self.attr("startOn").substr(9)).one("submit", {'uploader':self}, submitForm);
		}
		var fileExt = "";
		if(typeof(self.attr("fileExt"))!="undefined")
		{
			var fileExtSplit = self.attr("fileExt").split(",");
			for(var i=0; i<fileExtSplit.length; i++)
			{
				fileExt += "*."+fileExtSplit[i];
				if(i+1<fileExtSplit.length)
					fileExt += ";";
			}
		}
		var buttonImg = "";
		if(typeof(self.attr("button"))!="undefined")
			buttonImg = self.attr("button");
		var bwidth = 120;
		if(typeof(self.attr("bwidth"))!="undefined")
			bwidth = self.attr("bwidth");
		var bheight = 30;
		if(typeof(self.attr("bheight"))!="undefined")
			bheight = self.attr("bheight");
		var buttonText = "SELECT FILES";
		if(typeof(self.attr("buttonText"))!="undefined")
			buttonText = self.attr("buttonText");
		var customQueueId = "";
		if(typeof(self.attr("queueId"))!="undefined")
			customQueueId = self.attr("queueId");
		var maxSize = "";
		if(typeof(self.attr("maxSize"))!="undefined")
			maxSize = self.attr("maxSize");
		var uploadScript = "upload.php";
		if(typeof(self.attr("uploadScript"))!="undefined")
			uploadScript = self.attr("uploadScript");
		var wmode = "transparent";
		if(typeof(self.attr("wmode"))!="undefined")
			wmode = self.attr("wmode");
		var filesLimit = 999;
		if(typeof(self.attr("filesLimit"))!="undefined")
			filesLimit = self.attr("filesLimit");
		var sessionId = "";
		if(typeof(self.attr("sessionId"))!="undefined")
			sessionId = self.attr("sessionId");
		var ajax = "false";
		if(typeof(self.attr("ajax"))!="undefined")
			ajax = self.attr("ajax");
		var method= "post";
		if(typeof(self.attr("method"))!="undefined")
			method = self.attr("method");

		var scriptData = "'action':'upload', 'path':'"+self.attr('path')+"', 'PHPSESSID':'"+sessionId+"'";
		var fileDesc = "";
		if(typeof(self.attr("fileDesc"))!="undefined") {
			fileDesc = self.attr("fileDesc");
		}
		var fileType = "";
		if(typeof(self.attr("fileType"))!="undefined") {
			fileType = self.attr("fileType");
			scriptData += ", 'fileType':'" + self.attr("fileType") + "'";
		}
		if(typeof(self.attr("thumbnails"))!="undefined")
			scriptData += ", 'thumbnails':'" + self.attr("thumbnails") + "'";
		if(typeof(self.attr("thumbnailsFolders"))!="undefined")
			scriptData += ", 'thumbnailsFolders':'" + self.attr("thumbnailsFolders") + "'";
		if(typeof(self.attr("thumbnailsCrop"))!="undefined")
			scriptData += ", 'thumbnailsCrop':'" + self.attr("thumbnailsCrop") + "'";

		if(typeof self.uploadify == 'function')	{
		self.uploadify({
			'uploader'  : 'lib/file_upload/js/upload.swf',
			'script'    : uploadScript,
			'scriptData': eval('({' + scriptData + '})'),
			'queueID'	: customQueueId,
			'cancelImg' : 'lib/file_upload/close.png',
			'displayData' : (self.attr("onprogress")=="speed" ? "speed":"percentage"),
			'fileExt'	: fileExt,
			'fileDesc'	: fileDesc,
			'method'	: method,
			'buttonImg'	: buttonImg,
			'buttonText': buttonText,
			'wmode'		: wmode,
			'width'		: bwidth,
			'height'	: bheight,
			'sizeLimit'	: maxSize,
			'hideButton': (self.attr("hideButton")=="true" ? true:false),
			'auto'      : (self.attr("startOn")=="auto" ? true:false),
			'multi'		: (self.attr("multi")=="true" ? true:false),
			'queueSizeLimit' : filesLimit,
			'onSelect' : function(event, queueId, fileObj){
				if(self.attr("multi")!="true")
					if($("#"+queueId).html()!="")
						if(customQueueId!="")
							$("#"+customQueueId).html("");
						else
							$("#" + self.attr("id") + "Queue").html("");
			},
			'onSelectOnce' : function(event, data){
				if(self.attr("startOn")=="auto")
					updateUploadifySettings(self);
			},
			'onComplete' : function(event, queueId, fileObj, response, data){
				var responseJSON = $.parseJSON(response);
				if(typeof(responseJSON.error)!="undefined")
				{
					$("#" + self.attr("id") + queueId).html(responseJSON.error);
					return false;
				}
				else
				{
					if(self.attr("startOn").substr(0, 8)=="onSubmit")
						$("#"+self.attr("startOn").substr(9)).append("<input type='hidden' name='IMUFiles[]' value='"+responseJSON.filename.replace("'", "%27")+"' />");
					if(self.attr("afterUpload")=="link" || self.attr("afterUpload")=="filename" || self.attr("afterUpload")=="image" || self.attr("afterUpload")=="none")
					{
						$("#" + self.attr("id") + queueId + " .uploadifyProgress").animate({opacity: 0}, 500, function(){$(this).remove();});
						$("#" + self.attr("id") + queueId).html((self.attr("allowRemove")=="true" ? "<div class='cancel'><input class='button_cancel' name='removeFile' filename='"+responseJSON.filename.replace("'", "%27")+"' type='button'></div>":"") + (self.attr("afterUpload")=="link" || self.attr("afterUpload")=="image" ? "<a href='" + responseJSON.path + responseJSON.filename.replace("'", "%27") + "' target='_blank'>":"") + (self.attr("afterUpload")=="image" && (responseJSON.extension.toLowerCase()=="jpg" || responseJSON.extension.toLowerCase()=="jpeg" || responseJSON.extension.toLowerCase()=="bmp" || responseJSON.extension.toLowerCase()=="png" || responseJSON.extension.toLowerCase()=="tiff" || responseJSON.extension.toLowerCase()=="gif")  ? "<img class='uploadedImage' src='" + responseJSON.path + responseJSON.filename.replace("'", "%27") +"' />":(self.attr("afterUpload")!="none" ? "<span class='fileName'>"+fileObj.name+"</span>" : "")) + (self.attr("afterUpload")=="link" || self.attr("afterUpload")=="image" ? "</a>":""));
						if(typeof(self.attr("thumbnailsAfterUpload"))!="undefined")
						{
							var thumbnailsAfterUploadSplit = self.attr("thumbnailsAfterUpload").split(",");
							var thumbnailsFoldersSplit = new Array();
							if(typeof(self.attr("thumbnailsFolders"))!="undefined")
								thumbnailsFoldersSplit= self.attr("thumbnailsFolders").split(",");
							for(var i=0; i<thumbnailsAfterUploadSplit.length; i++)
							{
								display = $.trim(thumbnailsAfterUploadSplit[i]);
								folder = ($.trim(thumbnailsFoldersSplit[i])=="" ? self.attr("path") : $.trim(thumbnailsFoldersSplit[i]));
								if(display!="filename" && display!="image" && display!="link")
									$("#" + self.attr("id") + queueId).append("<span class='afterUploadThumbnail'>" + display + "</span>");
								else
									$("#" + self.attr("id") + queueId).append("<span class='afterUploadThumbnail'>" + (display=="link" || display=="image" ? "<a href='" + folder + responseJSON.thumbnails[i].replace("'", "%27") + "' target='_blank'>":"") + (display=="image" && (responseJSON.extension.toLowerCase()=="jpg" || responseJSON.extension.toLowerCase()=="jpeg" || responseJSON.extension.toLowerCase()=="bmp" || responseJSON.extension.toLowerCase()=="png" || responseJSON.extension.toLowerCase()=="tiff" || responseJSON.extension.toLowerCase()=="gif")  ? "<img class='uploadedThumbnail' src='" + folder + responseJSON.thumbnails[i].replace("'", "%27") + "' />":"<span class='fileName'>" + "thumb" + i + "_" + fileObj.name + "</span>") + (display=="link" || display=="image" ? "</a>":"") + "</span>");
							}
						}
						return false;
					}
				}
			},
			'onAllComplete' : function(event, data){
				if(typeof(self.attr("afterUpload"))!="undefined" && self.attr("afterUpload")!="link" && self.attr("afterUpload")!="filename" && self.attr("afterUpload")!="image" && self.attr("afterUpload")!="none")
				{
					var message = self.attr("afterUpload");
					message = message.replace("IMUfilesUploaded", data.filesUploaded);
					message = message.replace("IMUerrors", data.errors);
					message = message.replace("IMUtotalSizeB", data.allBytesLoaded);
					message = message.replace("IMUtotalSizeKB", roundNumber(data.allBytesLoaded/1024, 2));
					message = message.replace("IMUtotalSizeMB", roundNumber(data.allBytesLoaded/1024/1024, 2));
					message = message.replace("IMUtotalSizeGB", roundNumber(data.allBytesLoaded/1024/1024/1024, 2));
					message = message.replace("IMUspeedB", roundNumber(Math.round(data.speed*1024), 2));
					message = message.replace("IMUspeedKB", roundNumber(Math.round(data.speed), 2));
					message = message.replace("IMUspeedMB", roundNumber(Math.round(data.speed/1024), 2));
					message = message.replace("IMUspeedGB", roundNumber(Math.round(data.speed/1024/1024), 2));
					$("#" + self.attr("id") + "Queue").html(message);
				}
				if(self.attr("startOn").substr(0, 8)=="onSubmit")
				{
					var form = $("#"+self.attr("startOn").substr(9));
					form.unbind("submit", preventSubmit);
					if(ajax=="true")
					{
						var data = form.serializeArray();
						var url = form.attr("action");
						var method = form.attr("method");
						if(typeof(self.attr("ajaxLoaderId"))!="undefined")
							$("#"+self.attr("ajaxLoaderId")).css("display", "inline");
						$.ajax({
							url: url,
							data: data,
							type: method,
							async: false,
							success: function(data){
								if(typeof(self.attr("ajaxInfoId"))!="undefined")
								{
									$("#"+self.attr("ajaxInfoId")).html("");
									$("#"+self.attr("ajaxInfoId")).html(data).css("display", "block");
								}
								form[0].reset();
								$("[name='IMUFiles[]']").remove();
								if(typeof(self.attr("queueId"))!="undefined")
									$("#"+self.attr("queueId")).html("");
								else
									$("#" + self.attr("id") + "Queue").html("");
								if(typeof(self.attr("ajaxLoaderId"))!="undefined")
									$("#"+self.attr("ajaxLoaderId")).css("display", "none");
								form.one("submit", {'uploader':self}, submitForm);
							}
						});
					}
					else
						form.submit();
				}
			},
			'onError': function (event, queueID ,fileObj, errorObj) {
				/* if you got some problems just uncomment this code for debugging */
				/*var msg;
				if (errorObj.info == 404)
				   msg = 'Could not find upload script.';
				else if(errorObj.type === "HTTP")
				   msg = errorObj.type+ ": " +errorObj.info;
				else if(errorObj.type ==="File Size")
				   msg = fileObj.name+ ": " +errorObj.type;
				else
				   msg = errorObj.type+ ": " +errorObj.info;
				alert(msg);
				return false;*/
            }
		});
		}

		if(typeof(self.attr("allowRemove"))!="undefined") {

		if(self.attr("allowRemove")=="true")
		{
			$("#"+(customQueueId!="" ? customQueueId:self.attr("id")+"Queue")+" [name=removeFile]").on("click", function(){
				var selfRemove = $(this);
				if(typeof(self.attr("removeData"))!="undefined")
				{
					var customRemoveData = eval('({' + self.attr("removeData") + '})');
					var data="";
					for(var name in customRemoveData)
					{
						data += "'" + name + "':";
						if(customRemoveData[name].substr(0,9)=="selector:")
							data += "'" + $(customRemoveData[name].substr(9).toString()).val() + "',";
						else
							data += "'" + customRemoveData[name] + "',";
					}
					data = data.substr(0, data.length-1);
					data = eval('({' + data + '})');
				}
				$.ajax({
							url: uploadScript,
							data: "action=remove&filename="+selfRemove.attr("fileName")+(typeof(data)!="undefined" ? "&"+$.param(data) : ""),
							type: "POST",
							async: false,
							success: function(data){
									if(data!="")
										alert(data);
									else
										selfRemove.parent().parent().animate({opacity: 0}, 500, function(){$(this).remove();});
							}
					});
			});
		}
	}

	});

}




