var product = {
	searchURL : '/products/list',
  categorySearchURL : null,
	numOfDraggableImages : null,
	imageSorter : null, 
  addFileField : function() {
    //var ps = $('image_div').getElementsByTagName('p')
		var ps = $('progressTemplate').getElementsByTagName('p')
    for(var i=0;i<ps.length;i++){
      if (ps[i].getElementsByTagName('input')[0].value == '') return false
    }
    var newField = ps[0].cloneNode(true)
    newField.getElementsByTagName('input')[0].value = ''
    $('image_div').appendChild(newField)
  },
  shippingIsBilling : function(el) {
    if (el.checked) {
      $('order_billing_first_name').value = $F('order_shipping_first_name')
      $('order_billing_last_name').value = $F('order_shipping_last_name')
      $('order_billing_company_name').value = $F('order_shipping_company_name')
      $('order_billing_address').value = $F('order_shipping_address')
      $('order_billing_address_2').value = $F('order_shipping_address_2')
      $('order_billing_city').value = $F('order_shipping_city')
      $('order_billing_state').value = $F('order_shipping_state')
      $('order_billing_zip_code').value = $F('order_shipping_zip_code')
    }
  },
	changeSearchURL : function(sel) {
	  if (sel.form.action.indexOf(product.searchURL) == -1) {
	    product.categorySearchURL = sel.form.action
	  } 
	  if ($F(sel) == 'all') {
      sel.form.action = product.searchURL
	  } else {
	    sel.form.action = product.categorySearchURL
	  }
  },
  showAction : function(id) {
	Element.show('product_action_' + id)  
  },
  hideAction : function(id) {
	Element.hide('product_action_' + id)  
  },
  showCatAction : function(id) {
	Element.show('pe_category_action_' + id)  
  },
  hideCatAction : function(id) {
	Element.hide('pe_category_action_' + id)  
  },
  deleteImage : function(el,id) {
    if (!confirm('Are you sure?')) return false
    Element.remove(el)
    html = '<input name="dead_images[]" value="' +id + '" type="hidden"/>'
    new Insertion.Bottom('image_div', html)
  },
  showImage : function(el,options) {
    var tag  = options && options.tag ? options.tag : 'img'
    var imgs = $(el).getElementsByTagName(tag)
    for(var i=0;i<imgs.length;i++){
      if (imgs[i].style.display != 'none') {
        Element.hide(imgs[i])
      }
    }
	Element.show(options.current)
  },
	livegridHelper : {		 
	   notice      : function(text) {
			 $('product_notice').innerHTML = text
			 $('product_notice').style.visibility = ''
		 },
		 preview     : function(row) {
			 this.notice('Loading...')
			 this.removeCurrentRowClass();
			 Element.addClassName(row,'current_row');
			 new Ajax.Request('/products/preview/' + livegrid.currentRowId(row),{method :"post"})
		 },
		 clearNotice : function() {
			 $('product_notice').innerHTML = ''
			 $('product_notice').style.visibility = 'hidden'
		 },
		 removeCurrentRowClass : function() {
			  $$('tr').each(function(row) {
				  Element.removeClassName(row,'current_row');
			 });
		 }
	},
	reorderImages : function() {
		//Gets called when the order changes for dragging
		var images = $$('#caption_admin_div img.image_no_action_border')
		var paramsAry = images.inject([],function(array,image){ 
									 image.style.zIndex = 1;
									 var imageId = image.id.replace(/image_/,'')
									 if (imageId) {
								     array.push('reorder_images[]=' + imageId ) 
									 }
									 return array
								 } 
							 ).uniq()
		var params = paramsAry.join('&')
		//First time through set the length because dragging can change the true value
		//Also set default order
	  if (!product.numOfDraggableImages) {
			product.numOfDraggableImages = images.length
			product.currentImageOrder = params
			return false;
		}
		if (product.numOfDraggableImages == paramsAry.length && (!product.currentImageOrder || product.currentImageOrder != params)) {
			product.currentImageOrder = params
			new Ajax.Request('/products/move_list',{parameters : params, method : "post" })
		} 
	},
	showImageForm : function(id) {
	//Only show one at a time
		if (!$('image_action_' + id).visible()) {
		  product.showAction(id);
		  $('image_wrapper_' + id).style.height = '100px'
		} 
	},
	hideImageForm : function(id,force) {
		product.hideAction(id);
		if ( (!$('image_action_' + id).visible() && $('image_wrapper_' + id).style.height == '100px') || force) {
		  $('image_wrapper_' + id).style.height = '120px'
		}
	},
	adjustImageForTextField : function(id) {
		$('image_wrapper_' + id).style.height = '40px'
	},
	showImageStatus : function(id) {
		product.hideAction(id);
		$('image_wrapper_' + id).style.height = '100px'
		$('image_action_' + id).show();
	},
	startSorter : function() {
		if (!product.imageSorter) { 
		  product.imageSorter = true;
			new PeriodicalExecuter(product.reorderImages, 1);
		}
	},
	resetImageBorders : function() {
    var images = $('image_div').getElementsByTagName('img')
    for(var i=0;i<images.length;i++) {
      Element.removeClassName(images[i],'image_action_border')
      if (!Element.hasClassName(images[i],'image_no_action_border')) {
        Element.addClassName(images[i],'image_no_action_border')
      }
    }
  }
} 
var orders = {
  toggleNotes : function(el) {
    orders.linkToggle({link : el, initText : "Add Notes",secondText : "Hide Notes",
      onInit : function()   { Element.hide('order_notes_div','save_order');Element.show('order_notes_text_div')},
      onSecond : function() { Element.show('order_notes_div','save_order');Element.hide('order_notes_text_div')} 
     })
  },
  linkToggle : function(options) {
    if (options.link.innerHTML == options.initText) {
      $(options.link).innerHTML = options.secondText
      if (options.onSecond) options.onSecond()
    } else {
      $(options.link).innerHTML = options.initText
      if (options.onInit) options.onInit()
    }
  }
}
var imageGallery = {
  arrowLeft : function(el,options) {
    var tag  = options && options.tag ? options.tag : 'img'
    var hide = options && options.hideOption ? options.hideOption : 'display'
    var imgs = $(el).getElementsByTagName(tag)
    var firstImage = imgs[0]
    for(var i=0;i<imgs.length;i++){
      if (imgs[i].style.display != 'none') {
        Element.show(imgs[i-1])
        Element.hide(imgs[i])
        this.toggleArrows(i-1,imgs.length,hide)
        return
      }
    }
  },
  arrowRight : function(el,options) {
    var tag  = options && options.tag ? options.tag : 'img'
    var hide = options && options.hideOption ? options.hideOption : 'display'
    var imgs = $(el).getElementsByTagName(tag)
	
    for(var i=0;i<imgs.length;i++){
      if (imgs[i].style.display != 'none') {
        Element.show(imgs[i+1])
        Element.hide(imgs[i])
        this.toggleArrows(i+1,imgs.length,hide)
        return
      }
    }
  },
  toggleArrows : function(num, total,hide) {
    if (num == total - 1) {
      imageGallery.hideElement('image_right',hide)
    } 
    if (num == 0) {
      imageGallery.hideElement('image_left',hide)         
    }
    if (num == 1 && total != 1) {
      imageGallery.showElement('image_left',hide)
    }
    if (num == total - 2) {
      imageGallery.showElement('image_right',hide)
    } 
  },
  hideElement : function(el, hideType) {
    if (hideType == 'visibility') {
      $(el).style.visibility = 'hidden'
    } else {
      Element.hide(el)
    }
  },
  showElement : function(el, hideType) {
    if (hideType == 'visibility') {
      $(el).style.visibility = ''
    } else {
      Element.show(el)
    }
  }
}
function linkToggle(el, linkEl, onHideText,onShowText,options) {
  if (Element.visible(el)) {
		 if (typeof options != 'undefined' && options.onHide) { options.onHide() }
    $(linkEl).innerHTML = onShowText
  } else {
		if (typeof options != 'undefined' && options.onShow) { options.onShow() }
    $(linkEl).innerHTML = onHideText
  }
}

var uploadMovie = {
		  articleID : null,
			uploaderID : 0, //Counter for new upload swfs
			actionID : null, //The swf currently in use
			
			obj : function() {
				//var uploadName = id ? 'uploader_' + id : 'uploader'
				var uploadName = 'uploader'
			  if (navigator.appName.indexOf("Microsoft") != -1) {
          return window[uploadName];
        } else {
          return document[uploadName];
        }
			},
			
			browse : function(id) {
				//Make sure ID is set for progressbar updating
				//this.obj(id).setName(id);
			  this.obj().browse(id);
			},
			browseFile : function(str,len) {
				alert('Uploading ' + str + " len " + len);
			},
			fileNameEmpty : function(uploadNum) {
			  $(uploadMovie.pWrapper()).hide();
			  $(uploadMovie.pUploader(uploadNum)).show();
			  alert('Please choose a picture to upload' + uploadNum);
			},
			uploadComplete : function(response) {
			  $('caption_admin_div').update(response);
				 //$(uploadMovie.pWrapper()).hide();
				response.evalScripts();
			},
			uploadTotalComplete : function() {
				$('manage_images').hide();
				//$(uploadMovie.pWrapper()).hide();
				$('product_form').submit();
			},
			uploadProgress : function(response) {
				var pct = Math.round((response.bytesLoaded / response.bytesTotal * 100) * 10)/10 + '%';
			  $(uploadMovie.pStatus()).setStyle({background : "red",width : pct,height : '20px'});
				$(uploadMovie.pTextStatus()).update(response.uploadMessage + " " + pct)
				//if (response.bytesLoaded == response.bytesTotal) {
				  //$(uploadMovie.pTextStatus()).update('Saving ' +  filename)
				//} else {
				  //$(uploadMovie.pTextStatus()).update(pct)
				//}
			},
			selectedFile : function(name,uploadNum) {
				var filename = uploadNum ? 'filename_' + uploadNum : 'filename'
			  $(filename).value = name
				uploadMovie.addFile();
			},
			//Uploads files in there are any, and saves article
			upload : function(id,uploadNum) {
				if (id) { uploadMovie.articleID = id }
				//No files
				//alert(uploadMovie.getCaptions())
				
				if (uploadMovie.uploaderID == 0) {
				  $('product_form').submit();	
				  return
				}
				$('save_product_button').disabled = true;

			  $(uploadMovie.pWrapper()).show();
				$('progressTemplate').hide();
			  $(uploadMovie.pStatus()).setStyle({background : "red",width : 0,height : '20px'});
        var params = uploadMovie.articleID ? 'id=' + uploadMovie.articleID : ''
        this.obj().upload('/products/uploader?' + params,uploadMovie.getCaptions());
				uploadMovie.removeFileContainers();
			},
			addFile : function() {
				//$('uploadButton').show();
				uploadMovie.uploaderID += 1;
				var uploadHTML = $('progressTemplate').innerHTML;
				uploadHTML = uploadHTML.replace('uploadMovie.browse()','uploadMovie.browse(' + uploadMovie.uploaderID + ')');
				//change fields progressMainContainer,filename,progressHeader,progressWrapper,
				//progressUploader,status,textStatus,image_caption
				uploadHTML = uploadHTML.replace(/id="?filename"?/,'id="filename_' + uploadMovie.uploaderID + '"');
				
				uploadHTML = uploadHTML.replace(/class="?progressUploader"?/,'class="progressUploader" id="progressUploader_' + uploadMovie.uploaderID + '"');
				uploadHTML = uploadHTML.replace(/class="?progressMainContainer"?/,'class="progressMainContainer" id="progressMainContainer_' + uploadMovie.uploaderID + '"');
				uploadHTML = uploadHTML.replace(/class="?progressHeader"?/,'class="progressHeader" id="progressHeader_' + uploadMovie.uploaderID + '"');
				uploadHTML = uploadHTML.replace(/id="?image_caption"?/,'id="image_caption_' + uploadMovie.uploaderID+'"');
				//alert(uploadHTML);
				new Insertion.Bottom('newImageWrapper',uploadHTML);
				$('filename_'+uploadMovie.uploaderID).value = ''
				$('image_caption_'+uploadMovie.uploaderID).value = '';
			},
			getCaptions : function() {
			  var ary = []
				for(var i=0;i<=uploadMovie.uploaderID;i++) {
					//alert(uploadMovie.pCaption(i));
					if ($(uploadMovie.pCaption(i))) {
					  ary[i] = $F(uploadMovie.pCaption(i));
					}
				}
				return ary;
			},
			removeFileContainers : function() {
				for(var i=1;i<=uploadMovie.uploaderID;i++) {
					if ($(uploadMovie.pMainContainer(i))) {
					  $(uploadMovie.pMainContainer(i)).remove();
					}
				}
			},
			createUploader : function(id) {
				var tag = new FlashTag('/sprout/swfs/uploader.swf', 0, 0); 
		    tag.version = '9,0,45,0';
		    tag.setId('uploader_' + id);
				$('hidden_flash').innerHTML = $('hidden_flash').innerHTML + tag.toString();
			},
			//Helper functions for dynamnic elements
			pWrapper : function(uploadNum) {
				return 'statusTopWrapper'
			},
			pFileName : function(uploadNum) {
				return uploadNum ? 'filename_' + uploadNum : 'filename'
			},
			pUploader : function(uploadNum) {
				return uploadNum ? 'progressUploader_' + uploadNum : 'progressUploader'
			},
			pHeader : function(uploadNum) {
				return uploadNum ? 'progressHeader_' + uploadNum : 'progressHeader'
			},
			pStatus  : function(uploadNum) {
				return uploadNum ? 'status_' + uploadNum : 'status'
			},
			pTextStatus  : function(uploadNum) {
				return uploadNum ? 'textStatus_' + uploadNum : 'textStatus'
			},
			pCaption : function(uploadNum) {
				return uploadNum && uploadNum != 0 ? 'image_caption_' + uploadNum : 'image_caption'
			},
			pMainContainer : function(uploadNum) {
				return uploadNum ? 'progressMainContainer_' + uploadNum : 'progressMainContainer'
			}
} 
