/**
*  DesignElement: can be graphic or text
**/
DesignElement = {
	surface : null,
	s: null,
	sPrev: 0,
	x: null,
	y: null,
	type: null,
	p: { height: 0, width: 0 },
	
	scaleBy : function (ratio) {
		if(ratio > 0) {
			this.s += 10;
			this.sPrev = -10;
		} else {
			this.s -= 10;
			this.sPrev = 10;
		}
		// only scale if the result will not be greater than the frame
		this.newHeight = (this.p.height * this.s/100);
		this.newWidth = (this.p.width * this.s/100);
		
		if (this.newHeight <= CTD.designFrame.height 
		    && this.newWidth * this.s/100 <= CTD.designFrame.width) {
		   this.scale(); 
		} else {
		  this.s += this.sPrev;
		}
	},

	scale : function ()
	{
	  if ($(CTD.elms.graphicImg)) {
  		this.s = parseInt(this.s);
  		new Effect.Scale(CTD.elms.graphicImg, this.s, { scaleFrom: (this.s + this.sPrev), scaleMode: { originalHeight: this.p.height, originalWidth:this.p.width}});
  		$(CTD.elms.scaleLabel).innerHTML = this.s;
  		$(CTD.fields.graphicScale).value = this.s;
  	}
	}
}

CTD = {
	
	initialize : function(urls, elms) {
	  this.urls = {
	    designProcess:        null,
	    designSelectGraphic:  null,
	    graphicUpload:        null,
	    generateText:         null,
	    fontLibrary:          null,
	    graphicLibrary:       null,
	    getFonts:             null,
	    cartAdd:              null,
	    saveForLater:         null
	  }
	  Object.extend(this.urls, urls || {});
	  
	  this.elms = {
	    designForm:     'design_process',
	    designWrap:     'designwrap',
      textAlign:      'div#textalign a',
  		product: 				'div#productsel a.selected',
  		category: 			'div#picktopnav a.selected',
  		designFrame:    'orangeframe', //o
  		designFrameImg: '/images/frame_orange.gif', 
  		colors:         'div#colors a.selected',
  		sizes:          'div#sizes a.selected',
  		sizes2:         'div#sizes2 a.selected',
  		scaleLabel:     'scalelabel',
  		indicator:      'indicator',
  		graphicPos:     'topleft', //d ?
  		graphicDiv:     'graphic_img',
  		graphicImg:     'designimage', //di
  		graphicControl: 'graphic_control',
  		textDiv:        'text_img',
  		textImg:        'textimage' 
    }
    Object.extend(this.elms, elms || {});
    
    this.fields = { 
      graphicScale:   'graphic_scale',
      graphicId:      'graphic_graphic_id',
      uploadGraphicId:    'upload_graphic_id',
      uploadGraphicScale: 'upload_graphic_scale',
      fontTypeId:     'text_font_type_id',
      fontId:         'text_font_id',
      textLeading:    'text_leading',
      textSize:       'text_size',
      text:           'text_custom_text',
      font:           'text_font_id',
      textColor:      'text_color',
      textAlign:      'text_align',
      bgColor:        'text_bgcolor'
    }
	},
	
	imageLoaded : function() {
		Element.hide(CTD.elms.indicator);
	},
	
	submitDesign : function (step, startover) {
    var queryString = '&step='+step;
    var submit = true;
    if (startover) {
      if ( confirm ('Are you sure you want to start over? Any unsaved changes to your design will be lost.')) {
        queryString += '&startOver=1';
      } else {
        return false;
      }
    }
    
  	new Ajax.Updater(
  		this.elms.designWrap, 
  		this.urls.designProcess,
  		{ asynchronous:true,
  			evalScripts:true,
  			onComplete:function(request, json){
  			  if ($(CTD.elms.indicator)) Element.hide(CTD.elms.indicator);
  				CTD.designCallback(step);
  			}, 
  			onLoading:function(request, json){
  				if ($(CTD.elms.indicator)) Element.show(CTD.elms.indicator)
  			},
  			parameters:Form.serialize(document.design_process)+queryString
  		}
  	);
  	return false;
  },
  
  submitToCart : function (form) {
    var error = this.preCartValidate();
    if (error) {
      alert(error);
      return false;
    } else {
      CTDWindows.showWaitDialog();
      form.onsubmit = null;
      form.target = '';
      form.action = this.urls.cartAdd;
      return true;
    }
  },
  
  saveForLater : function (form) {
    CTDWindows.showWaitDialog();
    form.onsubmit = null;
    form.target = '';
    form.action = this.urls.saveForLater;
    return true;
  },
  
  preCartValidate : function () {
    var error = false;
    if ($F('item_size_id') == '') {
      error = 'Please select a size before adding this to your cart';
    } else if ($F('item_quantity') == '' || $F('item_quantity') < 1) {
      error = 'Please add a quantity of at least 1 before adding this to your cart';
    } else if ($F('design_name') == '') {
      error = 'Please name your design';
    }
    
    return error;
  },
  
  selectGraphic : function(graphic_id) {	
  	new Ajax.Updater(
  		this.elms.graphicDiv, 
  		this.urls.designSelectGraphic,
  		{ asynchronous:true,
  			evalScripts:true,
  			onComplete:function(request, json){
  				Element.hide($(this.elms.indicator)); 
  			},
  			onLoading:function(request, json){
  				Element.show($(this.elms.indicator))
  			},
  			parameters:Form.serialize(document.design_process)+'&graphic_id='+graphic_id
  		}
  	);
  	return false;
  },

  uploadGraphic : function() {
  	var f = $(this.elms.designForm);
  	f.onsubmit = '';
  	f.action = this.urls.graphicUpload;
  	AIM.submit(f, { 'onStart': CTD.uploadStart, 'onComplete': CTD.uploadComplete});
  	f.submit();
  	return false;
  },
  
  uploadStart : function () {
    if ($(CTD.elms.indicator)) Element.show(CTD.elms.indicator)
	},
	
	uploadComplete : function (response) {
		$(CTD.elms.graphicDiv).innerHTML = response;
		if ($F(CTD.fields.uploadGraphicId)) {
		  $(CTD.fields.graphicId).value = $F(CTD.fields.uploadGraphicId)
		  if ($F(CTD.fields.uploadGraphicScale)) {
		    $(CTD.fields.graphicScale).value = $F(CTD.fields.uploadGraphicScale);
		  }
		  CTD.step2Callback();
		  Element.show(CTD.elms.graphicControl);
		}
		if ($(CTD.elms.indicator)) Element.hide(CTD.elms.indicator);
	},
	
  designCallback : function(stepNum) {
    var funcName = 'step' + stepNum + 'Callback';    
    if (typeof CTD[funcName] != "undefined") {
      CTD[funcName]();
    }
    if (typeof urchinTracker != "undefined") {
      urchinTracker('step' + stepNum);  
    }
  },

  step2Callback : function() {
    DesignElement.type = 'graphic';
    
    this.graphicPos = $(this.elms.graphicPos);
    this.graphicImg = $(this.elms.graphicImg); 
    this.setDesignFrame(this.elms.designFrame);

    if (this.graphicImg) {
    	DesignElement.p = { width: this.graphicImg.width, height: this.graphicImg.height };
    } else {
    	DesignElement.p = { width: 0, height: 0 };
    }
    
    DesignElement.s = $F(this.fields.graphicScale);
    DesignElement.scale();

    this.draggable = new Draggable(this.elms.graphicPos, {onDrag: CTD.constrainDraggable, onEnd: CTD.constrainDraggable });
    this.draggable.dragType = 'graphic';
  },
  
  step3Callback : function() {    
    DesignElement.type = 'text';
    
    this.graphicPos = $(this.elms.graphicPos);  //this is ok; it refers to the topleft div
    this.textImg = $(this.elms.textImg); 
    this.setDesignFrame(this.elms.designFrame);

    if (this.textImg) {
    	DesignElement.p = { width: this.textImg.width, height: this.textImg.height };
    } else {
    	DesignElement.p = { width: 0, height: 0 };
    }

    this.draggable = new Draggable(this.elms.graphicPos, {onDrag: CTD.constrainDraggable, onEnd: CTD.constrainDraggable });
    this.draggable.dragType = 'text';
  },
	
	setAlign : function(link, val) {
		var a = $$(this.elms.textAlign);
		for(var i=0; i<a.length; i++){
			a[i].className = '';
		}
		link.className = 'selected';
		$('text_align').value = val;
	},
	
	setDesignFrame : function(elm) {
	  this.designFrame = $(elm);
	  var dimensions = this.designFrame.getDimensions();
	  this.designFrame.width = dimensions.width;
	  this.designFrame.height = dimensions.height;
	},
	
	toggleFrame : function(link, defaultClassName) {
		var of = $(this.elms.designFrame);
		if (link.className.indexOf('selected') == -1) {
			of.style.backgroundImage = 'url(' + this.elms.designFrameImg + ')';
			link.className = 'selected ' + defaultClassName;
		} else {
			of.style.backgroundImage = 'none';
			link.className = defaultClassName;
		}
	},

	constrainDraggable : function (draggable, event) {
    var delta = draggable.currentDelta();
    var element = draggable.element;
    
    // perhaps we can do these calculations right after we create the draggable?
    if (CTD.draggable.dragType == 'graphic') {
      var d = {
        height: parseInt(CTD.graphicImg.offsetHeight),
        width: parseInt(CTD.graphicImg.offsetWidth)
      }
    } else {
      var d = {
        height: parseInt(CTD.textImg.offsetHeight),
        width: parseInt(CTD.textImg.offsetWidth)
      }
    }
    
		if (delta[1] < 0) element.style.top = '0';
		if (delta[0] < 0) element.style.left = '0';
    
		if (d.height + delta[1] > CTD.designFrame.height) {
			element.style.top = (CTD.designFrame.height - d.height) + 'px';
		}
		
		if (d.width + delta[0] > CTD.designFrame.width) {
			element.style.left = (CTD.designFrame.width - d.width) + 'px';
		}
		
		CTD.updatePos();
	},

	moveUp : function () {
		var top = parseInt(this.graphicPos.style.top.replace(/px/, ''));
		if (top > 0) this.graphicPos.style.top = (top - 1) + 'px';
		CTD.updatePos();
	},

	moveDown : function () {
	  if (this.draggable.dragType == 'text') {
	    var imgHeight = this.textImg.offsetHeight;
	  } else {
	    var imgHeight = this.graphicImg.offsetHeight;
	  }
		var bottom = parseInt(imgHeight) + parseInt(this.graphicPos.style.top.replace(/px/, ''));
		if (bottom < this.designFrame.width) this.graphicPos.style.top = (parseInt(this.graphicPos.style.top.replace(/px/, '')) + 1) + 'px';
		CTD.updatePos();
	},

	moveLeft : function () {
		var left = parseInt(this.graphicPos.style.left.replace(/px/, ''));
		if (left > 0) this.graphicPos.style.left = (left - 1) + 'px';
		CTD.updatePos();
	},

	moveRight : function () {
	  if (this.draggable.dragType == 'text') {
	    var imgWidth = this.textImg.offsetWidth;
	  } else {
	    var imgWidth = this.graphicImg.offsetWidth;
	  }
		var left = parseInt(this.graphicPos.style.left.replace(/px/, ''));
		if (parseInt(imgWidth) + left < this.designFrame.width) {
			this.graphicPos.style.left = (left + 1) + 'px';
		}
		CTD.updatePos();
	},

	updatePos : function () {
		var xpos = $(this.elms.graphicPos).style.left.replace(/px/,'');
		var ypos = $(this.elms.graphicPos).style.top.replace(/px/,'');
		$('xpos').innerHTML = xpos; //visible display
		$('ypos').innerHTML = ypos;
		$(DesignElement.type+'_x').value = xpos;//hidden form fields
		$(DesignElement.type+'_y').value = ypos;
	},

	changeDI : function (src) {
		CTD.di.src = src;
		p = { width: CTD.di.width, height: CTD.di.height };
	},
	
	selectProduct : function (link_id) {
		var links = $$(this.elms.product);
		for (var i=0; i<links.length; i++) {
			links[i].className = '';
		}
		$(link_id).className = 'selected';
	},

	selectCategory : function (link_id) {
		var links = $$(this.elms.category);
		for (var i=0; i<links.length; i++) {
			links[i].className = links[i].className.gsub('selected', '');
		}
		$(link_id).className += ' selected';
	},
	
	selectColor : function (color_id) {
		var colors = $$(this.elms.colors);
		for (var i=0; i<colors.length; i++) {
			colors[i].className = colors[i].className.gsub('selected', '');
		} 
		$(color_id).className += ' selected';
	},

  selectSize : function (size_id, selector) {
		var sizes = $$(selector);
		for (var i=0; i<sizes.length; i++) {
			sizes[i].className = sizes[i].className.gsub('selected', '');
		}
		$(size_id).className += ' selected';
	},
	
	genTextImage : function (evt) {
  	if ($(CTD.elms.indicator)) Element.show(CTD.elms.indicator);
  	var text_image = new Image();
  	text_image.onload = CTD.imageLoaded;

  	var text_leading = ($F(CTD.fields.textLeading) == 'standard') ? $F(CTD.fields.textSize) + 1 : $F(CTD.fields.textLeading);
  	var params = {
  		text: 	  $F(CTD.fields.text), 
  		font: 	  $F(CTD.fields.font),
  		color:    $F(CTD.fields.textColor),
  		size:     $F(CTD.fields.textSize),
  		align:    $F(CTD.fields.textAlign),
  		bgcolor:  $F(CTD.fields.bgColor),
  		leading:  text_leading
  	};

  	var hash = $H(params);
  	path = CTD.urls.generateText + '?' + hash.toQueryString();
  	text_image.src = path;
  	$('textimage').src = text_image.src;

  	return false;
  },
  
  updateSelectedFontType : function (fontTypeId, fontId) 
  {
    new Ajax.Request(
  		this.urls.getFonts,
  		{ asynchronous:true,
  			onComplete:function(request, json){
  				Element.hide($(CTD.elms.indicator)); 
  			},
  			onLoading:function(request, json){
  			  Element.show($(CTD.elms.indicator));
  			},
  			parameters: 'font_type_id='+fontTypeId+'&font_id='+fontId
  		}
  	);
  }  
}

// these rely on windows.js
CTDWindows = {
  showFontLibrary : function (fontTypeId, fontId)
  {   
    fontWin = new Window({
      className: 'mac_os_x',
      title: 'Font Library',
      width:400, 
      height:400,
      showEffectOptions: {duration:1.5},
      destroyOnClose: true,
      recenterAuto:true 
    });
    fontWin.setZIndex(100);
    fontWin.setURL(CTD.urls.fontLibrary+'?font_type_id='+fontTypeId+'&font_id='+fontId);
    fontWin.showCenter();                                          
  }, 
  
  showGraphicLibrary : function ()
  {   
    fontWin = new Window({
      className: 'mac_os_x',
      title: 'Graphic Library',
      width:545, 
      height:400,
      showEffectOptions: {duration:1.5},
      destroyOnClose: true,
      recenterAuto:true 
    });
    fontWin.setZIndex(100);
    fontWin.setURL(CTD.urls.graphicLibrary);
    fontWin.showCenter();                                          
  },
  
  showHelp : function (helpUrl) {
    Dialog.alert({ 
      url: helpUrl, 
      options: {method: 'get'}
    }, {
      className: "mac_os_x_dialog", 
      width:550, 
      okLabel: "thanks for the help!", 
      top:0,
      showEffect: Effect.ModalSlideDown, 
      hideEffect: Effect.ModalSlideUp, 
      showEffectOptions: {duration: 0.7, delay: 0.3}, 
      hideEffectOptions: {duration: 0.3}
    });
  },
  
  showWaitDialog : function () {    
    Dialog.info(
      "Please wait while we generate your design images.<br />This should only take a moment...", 
      { width:250, height:100, showProgress: true, className: "mac_os_x_dialog" }
    );
  }
}


/**
*  AJAX IFRAME METHOD (AIM)
*  http://www.webtoolkit.info/
**/
AIM = {
	frame : function(c) {
    var n = 'f' + Math.floor(Math.random() * 99999);
    var aim_d = document.createElement('DIV');
    aim_d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';
    document.body.appendChild(aim_d);

    var i = document.getElementById(n);
    if (c && typeof(c.onComplete) == 'function') {
      i.onComplete = c.onComplete;
    }

    return n;
	},

	form : function(f, name) {
	  f.setAttribute('target', name);
	},

	submit : function(f, c) {
    AIM.form(f, AIM.frame(c));
    if (c && typeof(c.onStart) == 'function') {
      return c.onStart();
    } else {
      return true;
    }
	},

	loaded : function(id) {
	  var i = document.getElementById(id);
	  if (i.contentDocument) {
	    var doc = i.contentDocument;
	  } else if (i.contentWindow) {
	    var doc = i.contentWindow.document;
	  } else {
	    var doc = window.frames[id].document;
	  }
	  if (doc.location.href == "about:blank") {
	    return;
	  }
	  if (typeof(i.onComplete) == 'function') {
	    i.onComplete(doc.body.innerHTML);
	  }
	}
}