
var ChargeDecorationLibrary = Class.create({
  CLASSDEF: {
      name: 'ChargeDecorationLibrary'
  },
  
  initialize: function(range1price, range2price, range3price, range4price, range5price, range6price, range7price) {
    this.range1price = range1price;
    this.range2price = range2price;
    this.range3price = range3price;
    this.range4price = range4price;
    this.range5price = range5price;
    this.range6price = range6price;
    this.range7price = range7price;
  }
});

var decorationLibrary = null; //this is the currently selected library 
var DecorationLibraryManager = Class.create({
  CLASSDEF: {
      name: 'DecorationLibraryManager'
  },
  
  initialize: function DLM_initialize(designer) {
    this.designer = designer;
    this.libraries = {};
    this.nextId = -1;
    this.imageSelectorFunction = this.selectImageInLibrary.bind(this);
    this.categorySelectorFunction = this.selectCategoryInLibrary.bind(this);
    this.imageUploadedFunction = this.imageUploaded.bind(this);
    this.doubleClickImageFunction =  this.doubleClickImage.bind(this);
  },
  
  getNextId: function DLM_getNextId() {
    return this.nextId--;
  },
  
  selectImage: function DLM_selectImage(productAreaProcess, callback) {
    this.selectImageCallback = callback;
    popup("decoration_libraries");
    this.productAreaProcess = productAreaProcess;
    this.currentProcessId = productAreaProcess.id;
    this.getLibrary(this.currentProcessId, function(library) {
        $("library_browser_" + this.currentProcessId).show();
    }.bind(this));
  },
  
  getLibrary: function DLM_getLibrary(processId, callback) {
    if(this.libraries[processId] == null) {
      $("declib_loading").show();
      var aKey = asyncStart("decoration_libraries_container");
      this.registerLibraryCallback = function() {
        asyncFinish(aKey);
        $("declib_loading").hide();
        decorationLibrary = this.libraries[processId];
        callback(decorationLibrary);
      }.bind(this);
      var modeStr = "";
      if(d.mode == DESIGNER_MODE_CONFIGURE) {
        modeStr="&for_product=1";
      }
      var ajax = new Ajax.Updater("decoration_libraries_container", d.ajaxUrl("/designer/get_library?process=" + processId + modeStr), {asynchronous:true, evalScripts:true, insertion: Insertion.Bottom}); 
    } else {
      decorationLibrary = this.libraries[processId];
      callback(decorationLibrary);
    }
  },
  
  registerLibrary: function DLM_registerLibrary(library, processId) {
    log("registerLibrary: " + processId);
    this.libraries[processId] = library;
    library.imageSelectionCallback = this.imageSelectorFunction; //track when a user selects an image...
    library.imageUploadedCallback = this.imageUploadedFunction; //track when a user uploads an image...
    library.categorySelectionCallback = this.categorySelectorFunction; //track when a user selects a category
    library.doubleClickImageCallback = this.doubleClickImageFunction; //track when user doublic clicks image...
    if(this.registerLibraryCallback != null) {
      this.registerLibraryCallback();
      this.registerLibraryCallback = null;
    }
  },
  
  close: function DLM_close() {
    $('image_details_' + decorationLibrary.process).style.display='none';
    closePopup("decoration_libraries");
    $("library_browser_" + decorationLibrary.process).style.display = "none";
    this.image = null;
  },
  
  selectImageInLibrary: function DLM_selectImageInLibrary(loading, image) {
    if(loading) {
		
      this.image = image;
      //$("image_details_" + this.currentProcessId).style.display="block";
							
      var dims = image.scale(250);
      queueImageLoading($("image_thumb_" + this.currentProcessId),image.url,dims[0],dims[1], function() {});
      $("existing_name_" + this.currentProcessId).innerHTML = image.name;
      var w = d.convertLengthFromInches(image.width / this.productAreaProcess.perfectDPI);
      var h = d.convertLengthFromInches(image.height / this.productAreaProcess.perfectDPI);
      $("decoration_size_field_" + this.currentProcessId).innerHTML = w.toFixed(2) + " x " + h.toFixed(2) + " " + d.getLengthUnit();
      //show declib price here
      if(image.decorationLibraryId == 0) {
        Element.hide("decoration_price_" + this.currentProcessId);
      } else {
        dec_price = d.chargeDecorationLibraries[image.decorationLibraryId];
        if(dec_price == null) {
          Element.hide("decoration_price_" + this.currentProcessId);
        } else {
          // only add markup if percent markup in use and not a custom product
          var percentMarkup = 1;
          var fixedMarkup = 0;
          if(d.currentCProduct.usingCustomProduct()) {
            // leave markup as %0
          } else if(d.defaultMarkupType == 0) {
            percentMarkup =  1 + d.defaultMarkupAmount / 100;
          }
          
          $("decoration_price_field_" + this.currentProcessId).innerHTML = "$" +( (dec_price.range1price + (d.declibMarkup / 100) * dec_price.range1price) * percentMarkup).toFixed(2);
          Element.show("decoration_price_" + this.currentProcessId);
        }
      }
	  						
	  						var int_y_pos=get_page_ypos($("dec_lib_li_"+image.uId));
							var int_x_pos=get_page_pos($("dec_lib_li_"+image.uId));
							
							var offset_x_pos=get_page_pos($$("#decoration_libraries .interior")[0]);
							var offset_y_pos=get_page_ypos($$("#decoration_libraries .interior")[0]);
							
							var tb_pos=get_page_pos($("decoration_list_container_div_"+this.currentProcessId))+$("decoration_list_container_div_"+this.currentProcessId).offsetWidth;
							var ep_pos=get_page_pos($("dec_lib_li_"+image.uId))+270;
							
							var diff=0;
							if(ep_pos>tb_pos){
								diff=tb_pos-ep_pos;
							}
							
							$("image_details_"+this.currentProcessId).style.width=eval(dims[0]+255)+"px";
							
							$("image_details_"+this.currentProcessId).style.display="block";
							$("image_details_"+this.currentProcessId).style.position="absolute";
							$("image_details_"+this.currentProcessId).style.left=parseInt(int_x_pos+diff-offset_x_pos)+"px";
							$("image_details_"+this.currentProcessId).style.top=parseInt(int_y_pos-offset_y_pos)+"px";
      
    } else {
      this.image = null;
      $("image_details_" + this.currentProcessId).style.display="none";
      return true;
    }
  },
  
  doubleClickImage: function DLM_doubleClickImage(image) {
    this.image = image;
    $("image_details_" + this.currentProcessId).style.display="none";
    this.selectCurrentImage();
  },
  
  selectCategoryInLibrary: function DLM_selectCategoryInLibrary(loading, category) {
    $("image_details_" + this.currentProcessId).style.display="none";
    return true;
  },
  
  imageUploaded: function DLM_imageUploaded(image) {
    var dims = image.scale(350);
    var img = $("copyright_preview");
    img.width = dims[0];
    img.height = dims[1];
    img.src = image.url;
    var process = processes.byId[d.newProcessId];
    
    this.confirmImage = image;
    popup("confirm_image_upload");
  },
  
  setConfirmResult: function DLM_setConfirmResult(result) {
    if(result == 0) { //cancel
      var t2 = new Ajax.Request(d.ajaxUrl(d.pathPrefix + "/shared/library/set_copyright_result?id=" + this.confirmImage.id + "&result=" + result), {asynchronous:true, evalScripts:true});
      this.confirmImage.remove();
      $('copyright_preview').src = "/images/trans.gif";
      $('copyright_selected').checked = false;
      closePopup("confirm_image_upload");
    } else {
      if(!$("copyright_selected").checked) {
        alert(ml("Please tick the checkbox"));
        return;
      }
      $('copyright_preview').src = "/images/trans.gif";
      $('copyright_selected').checked = false;
      closePopup("confirm_image_upload");
      var t2 = new Ajax.Request(d.ajaxUrl(d.pathPrefix + "/shared/library/set_copyright_result?id=" + this.confirmImage.id + "&result=" + result), {asynchronous:true, evalScripts:true});
      this.image = this.confirmImage;
      this.selectCurrentImage();
    }
  },
  
  selectCurrentImage: function DLM_selectCurrentImage() {
    if(this.image == null) {
      //handle when reloaded....
      var lib = this.libraries[this.currentProcessId];
      if(lib.selectedCat != null && lib.selectedCat.selectedImage != null) {
        this.image = lib.selectedCat.selectedImage;
      }
      if(this.image == null) {
        alert(ml("Please select an image"));
        return;
      }
    }
    var img = this.image;
    this.close();
    this.selectImageCallback(img);
    
  }
  
});

/* added by jonathan 28/10/09 */

function get_page_pos(elem){
	var x_pos = elem.offsetLeft;
	temp_el = elem.offsetParent;
	try {
		while (temp_el != null) {
			int_x=temp_el.offsetLeft;
			if(int_x) x_pos += temp_el.offsetLeft;
			temp_el = temp_el.offsetParent;
		}
	}
	catch(ex){}
	return x_pos;
	//return 40;
}

function get_page_ypos(elem){
	var y_pos = elem.offsetTop;
	temp_el = elem.offsetParent;
	try {
		while (temp_el != null) {
			int_y=temp_el.offsetTop;
			if(int_y) y_pos += temp_el.offsetTop;
			temp_el = temp_el.offsetParent;
		}
	}
	catch(ex){}
	return y_pos;
	//return 40;
}

