var PtpGifts = function(){
	var IMG_BASE_URL = "";
	var photo;
	
	var masterItems = new Object();
	var masterItemsIdx = new Array();
	
	var giftData = new Object();
	var giftDataIdx = new Array();
	
	//Vars
	var MainForm, MItemSel, MItemAttrs;
	var MainImg, MainGiftItemImg, MainGiftItemWrap, MainCanvas;
	var CurrentMitem, CurrentSkuId, CurrentMasterId;
	var CurrentAttrs, CurrentAttrSel, CurrentAttrIds, CurrentAttrOpsIds;
	var CurrentSkuOps, CurrentSkuOption, UseGiftImages; //skusetdata 'aux' options
	var CurrentProdId;
	
	var DidMove = false;
	var ShiftInverval = false;
	var SmallShift = 1;
	var LargeShift = 5;
	var IntervalTime = 10;
	
	var CurrentMotion = {};
	
	var didMotion = false;
	var alertOnNoMotion = null;
	
	//messageing
	var ptpOnPricePrefix = "";
	var ptpOnPricePostfix = "";
	var ptpMaskHideMessage = "Hide";
	var ptpMaskShowMessage = "Show";
	
	
	//custume on change function
	var onChange = null;
	var onFirstItemSelected = null;
	var onNoItemSelected = null;
	var onQuantityChange = null;

	//extra ajaxy submit call backs
	var useAjax = null;
	var onSubmit = null;
	
	function setImg(m, ur){
		m.src = ur;
		if(isIE){
			$s(m, 'background', 'none');
			m.src = '/providerasset/1/spacer.gif';
			m.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src="' +  ur +'");'
		}
	}
	
	function init_data(indata){
		IMG_BASE_URL = indata.IMG_BASE_URL;
		photo = indata.photo;
		masterItems = indata.masterItems;
		masterItemsIdx = indata.masterItemsIdx;
		giftData = indata.giftData;
		giftDataIdx = indata.giftDataIdx;

		onChange = indata['onChange'] || null;
		onFirstItemSelected = indata['onFirstItemSelected'] || null;
		onNoItemSelected = indata['onNoItemSelected'] || null;
		onQuantityChange = indata['onQuantityChange'] || null;

		ptpOnPricePrefix = indata['ptpOnPricePrefix'] || null;
		ptpOnPricePostfix = indata['ptpOnPricePostfix'] || null;
		ptpMaskHideMessage = indata['ptpMaskHideMessage'] || null;
		ptpMaskShowMessage = indata['ptpMaskShowMessage'] || null;
		
		alertOnNoMotion = indata['alertOnNoMotion'] || null;
		useAjax = indata['useAjax'] || null;
		onSubmit = indata['onSubmit'] || null;
	}
	
	function getOn(){
		CurrentMitem = $F(MItemSel);

		if(masterItems[CurrentMitem]){
			CurrentMitem = masterItems[CurrentMitem];
			CurrentMasterId = CurrentMitem.master_item_id;
			return CurrentMitem;
		}else{
			CurrentMitem = false;
		}
		return false;
	}
	
	function setAttributeSels()
	{
		getOn();
		if(!CurrentMitem){ return; }
		var m_id = CurrentMitem.master_item_id;
		var prods = CurrentMitem.products;
		var attrs = CurrentMitem.attributes;
		
		//given all the products, see what attributes are really allowed
		var got_attrs = {};
		
		//find attr selectors
		var have_attrs = new Array();
		for(var i=0;i<prods.length;i++){
			if(!giftData[prods[i]]){ continue; }
			var prod_attrs = giftData[prods[i]].attributes;
			for(var j=0; j<attrs.length;++j){
				var on_attr = attrs[j][0];
				if(prod_attrs[on_attr]){
					if(!got_attrs[on_attr]){ got_attrs[on_attr] = new Array(); }
					got_attrs[on_attr].push(prod_attrs[on_attr]);
				}
			}
		}
		for(var j=0; j<attrs.length;++j){
			var sel_id = "att_" + attrs[j][0] + "_" + m_id;
			var on_attr = attrs[j][0];
			if(!MainForm[sel_id]){ continue; }
			var old_v  = $F(MainForm[sel_id]);
			$F.clear(MainForm[sel_id]);
			if(!got_attrs[on_attr]){ 
				continue; //nothing to choose
			}
			var did = {};
			var op_ct = 0;
			for(var i =0;i<got_attrs[on_attr].length; ++i){
				if(did[got_attrs[on_attr][i][0]]){ continue; }
				MainForm[sel_id].options[op_ct] = new Option(got_attrs[on_attr][i][3], got_attrs[on_attr][i][0]);
				did[got_attrs[on_attr][i][0]] = 1;
				op_ct++;
			}
			hide(sel_id + "_des");
			if(old_v){ 
				$F.set(MainForm[sel_id], old_v); 
			}
			if(got_attrs[on_attr].length == 1){
				hide(MainForm[sel_id]);
				if($(sel_id + "_des")){
					$(sel_id + "_des").innerHTML = got_attrs[on_attr][0][3];
					show(sel_id + "_des");
				}
			}
		}
		var st = "";
		

		for(var i=0;i<MItemAttrs.length;i++){
			if(MItemAttrs[i].id == 'm_sel_' + CurrentMitem.master_item_id){
				show(MItemAttrs[i]);
			}else if(MItemAttrs[i].id == 'm_vops_' + CurrentMitem.master_item_id){
				show(MItemAttrs[i]);
			}else{
				hide(MItemAttrs[i]);
			}
		}
	}

	function getProductId(do_not_set_rendition)
	{
		getOn();
		if(!CurrentMitem){ return; }
		var att = CurrentMitem.attributes;
		CurrentAttrSel = new Array();
		CurrentAttrs = new Array();
		CurrentAttrIds = new Array();
		CurrentAttrOpsIds = new Array();
		CurrentProdId = false;
		var st = "";
		
		for(var i = 0; i<att.length; i++){
			if(MainForm["att_" + att[i][0] + "_" + CurrentMitem.master_item_id]){
				var got_f = MainForm["att_" + att[i][0] + "_" + CurrentMitem.master_item_id];
				CurrentAttrIds.push(att[i][0]);
				CurrentAttrSel.push(got_f);
				CurrentAttrOpsIds.push($F(got_f));
			}
		}
		
		var p_map = [];
		//based on prids and attrs pick the prid ID
		for(var i=0;i<CurrentMitem.products.length;i++){
			if(!giftData[CurrentMitem.products[i]]){
				continue;
			}
			var on_p = giftData[CurrentMitem.products[i]];
			//if multi attr per prod, need to map them out
			var got_p = 0;
			for(var j=0;j<CurrentAttrIds.length;j++){
				if(on_p.attributes[CurrentAttrIds[j]] && on_p.attributes[CurrentAttrIds[j]][0] == CurrentAttrOpsIds[j]){
					p_map[got_p++] = [CurrentMitem.products[i], on_p];
				}else{
					got_p = false;
				}
			}
			if(CurrentAttrIds.length == 0){
				p_map[0] = [CurrentMitem.products[i], on_p];
			}
		}
		if(p_map.length || CurrentAttrIds.length == 0){
			CurrentProdId = p_map[p_map.length -1][0];
			CurrentSkuId = p_map[p_map.length -1][1].sku_id;
		}
		if(CurrentProdId){
			//get any 'options/sku data bits for master item
			CurrentSkuOps = false;
			UseGiftImages = false;
			var got_selops = MainForm["selop_" +  CurrentMitem.master_item_id];
			if(got_selops){
				// if the current pid does not have any options, 'hide it'
				if(!giftData[CurrentProdId]['options']){
					$s('m_vops_' + CurrentMitem.master_item_id, 'display', 'none');
				}else{
					$s('m_vops_' + CurrentMitem.master_item_id, 'display', 'block');
					CurrentSkuOps = got_selops;
					if(CurrentSkuOps){ 
						CurrentSkuOption = CurrentSkuOps.options[CurrentSkuOps.selectedIndex].value; 
					}else{
						CurrentSkuOption = false;
					}
					if(giftData[CurrentProdId].view_name == CurrentSkuOption){
						UseGiftImages = giftData[CurrentProdId]
					}else{
						for(var i=0;i<giftData[CurrentProdId].options.length;i++){
							if(giftData[CurrentProdId].options[i].view_name == CurrentSkuOption){
								UseGiftImages = giftData[CurrentProdId].options[i];
							}
						}
					}
				}
			}
			MainForm.prod.value = CurrentProdId;
			MainForm.sku.value = CurrentSkuId;
			
			priceSw(CurrentProdId);
			adjustDimsForProd(CurrentProdId, do_not_set_rendition);
		}
	}
	function shiftZoom(dir){
		didMotion = true;
		function do_shift(){
			CurrentMotion.img_h += SmallShift * parseInt(dir);
			var w_diff  = CurrentMotion.img_w - CurrentMotion.img_h * photo.asp;
			CurrentMotion.img_w = CurrentMotion.img_h * photo.asp;
			CurrentMotion.img_w_t -= SmallShift * parseInt(dir) / 2;
			CurrentMotion.img_w_l += w_diff / 2;
			adjustImageMask();
		}
		do_shift();
		ShiftInverval = setInterval(do_shift, IntervalTime);
	}
	
	function shiftLR(dir){
		didMotion = true;
		function do_shift(){
			CurrentMotion.img_w_l += SmallShift * parseInt(dir);
			adjustImageMask();
		}
		do_shift();
		ShiftInverval = setInterval(do_shift, IntervalTime);
	}
	function shiftTB(dir){
		didMotion = true;
		function do_shift(){
			CurrentMotion.img_w_t += SmallShift * parseInt(dir);
			adjustImageMask();
		}
		do_shift();
		ShiftInverval = setInterval(do_shift, IntervalTime);
	}
	function dbg(b){
		var st = "";
		if(typeof(b) == typeof("")){
			$('log').innerHTML = "----<br />" + b + "<br />" + $('log').innerHTML;
			return;
		}
		for(var el in b){
			st += el + ": " + b[el] +"<br />";
		}
		$('log').innerHTML = "----<br />" + st + $('log').innerHTML;
	}
	function encodeCropStr(CropData){
		var arr = ['print_width', 'print_height', 'crop_rotation', 'crop_x', 'crop_y', 'crop_width', 'crop_height', 'border_color', 'border_left', 'border_right', 'border_top', 'border_bottom', 'type', 'photo_orig_width', 'photo_orig_height', 'open_width', 'open_height','view_name'];
		var st = new Array();
		for(var i=0;i<arr.length;i++){
			if(CropData[arr[i]] != undefined){
				st.push(CropData[arr[i]]);
			}else{
				st.push("");
			}
		}
		return st.join(",");
	}
	
	function decodeCropStr(in_st, prod){
		prod = prod || CurrentProdId;
		if(!giftData[prod]){ return; }
		if(!CurrentMotion){ return; }
		var on_p = giftData[prod];
		
		var arr = ['print_width', 'print_height', 'crop_rotation', 'crop_x', 'crop_y', 'crop_width', 'crop_height', 'border_color', 'border_left', 'border_right', 'border_top', 'border_bottom',  'type', 'photo_orig_width', 'photo_orig_height', 'open_width', 'open_height', 'view_name'];
		var pl = in_st.split(",");
		var st = new Object();
		for(var i=0;i<arr.length;i++){
			st[arr[i]] = pl[i]?pl[i]:0;
		}
		//the view name has the 'web crop bits'
		var spl = st.view_name.split("|");
		CurrentMotion.open_height = parseInt(st.open_height);
		CurrentMotion.open_width = parseInt(st.open_width);
		CurrentMotion.photo_orig_width = parseInt(st.photo_orig_width);
		CurrentMotion.photo_orig_height = parseInt(st.photo_orig_height);
		CurrentMotion.img_w_t = parseInt(spl[0]);
		CurrentMotion.img_w_l = parseInt(spl[1]);
		CurrentMotion.img_w = parseInt(spl[2]);
		CurrentMotion.img_h = parseInt(spl[3]);

		adjustImageMask()
		
		return st;
	}
	
	function stopMotion(prod)
	{
		if(ShiftInverval){ clearInterval(ShiftInverval); }
		
		//compute the rendition string
		//3.51,3.51,0,67,1,264,264,white,0,0,0,0,fixed_border,400,267,125,125,<370,363,260,173,0,>
		//print_width,print_height,crop_rotation,crop_x,crop_y,crop_width,crop_height,
		//border_color,border_left,border_right,border_top,border_bottom,
		//type,photo_w,photo_h,window_w,window_h, view_name
		
		prod = prod || CurrentProdId;
		if(!giftData[prod]){ return; }
		if(!CurrentMotion){ return; }
		var on_p = UseGiftImages || giftData[prod];
		
		//the acctualy 'scale' of the x,y,w,h based on the Real Image dims
		//no zoom either means we have borders on allsides, OR that 
		// the image height = the holes height (as that is our starting point)
		// thus if the imageheight > holesheight, we zoomed and by that ratio
		// then out 'crop_x (if > 0) is 
		var zoom_scale = CurrentMotion.img_h / CurrentMotion.open_height;
		var image_zoom = photo.height / CurrentMotion.open_height;
		var t_h = CurrentMotion.canv_h / on_p.ppi;
		var t_w = CurrentMotion.canv_w / on_p.ppi;
		
		//crop is the 'Canvas' dims insertsection on to the image
		var crop_x = CurrentMotion.img_w_l - CurrentMotion.canv_left;
		var b_left, b_right, b_top, b_bottom;
		b_right = 0;
		b_left = 0;
		if(CurrentMotion.img_w_l > CurrentMotion.canv_left){
			crop_x = 0;
			b_left = CurrentMotion.img_w_l - CurrentMotion.canv_left;
		}
		crop_x = crop_x < 0?-crop_x:crop_x;
		if(CurrentMotion.img_w_l + CurrentMotion.img_w < CurrentMotion.canv_left + CurrentMotion.canv_w){
			b_right = CurrentMotion.canv_left + CurrentMotion.canv_w - CurrentMotion.img_w - CurrentMotion.img_w_l;
		}
		var crop_width = CurrentMotion.canv_w - b_left - b_right;
		b_top = 0;
		b_bottom = 0;
		var crop_y = CurrentMotion.img_w_t - CurrentMotion.canv_top;
		if(CurrentMotion.img_w_t > CurrentMotion.canv_top){
			crop_y = 0;
			b_top = CurrentMotion.img_w_t - CurrentMotion.canv_top
		}
		crop_y = crop_y < 0?-crop_y:crop_y;
		if(CurrentMotion.img_w_t + CurrentMotion.img_h < CurrentMotion.canv_top + CurrentMotion.canv_h){
			b_bottom = CurrentMotion.canv_top + CurrentMotion.canv_h - CurrentMotion.img_h - CurrentMotion.img_w_t;
		}
		var crop_height = CurrentMotion.canv_h - b_top - b_bottom;
				
		//image width
		if((CurrentMotion.img_w_l + CurrentMotion.img_w ) < (CurrentMotion.canv_w - CurrentMotion.canv_left) && crop_x == 0){
			crop_width = photo.width; //rounding avoids
		}
		//image heigh
		if((CurrentMotion.img_w_t + CurrentMotion.img_h ) < (CurrentMotion.canv_h - CurrentMotion.canv_top) && crop_y == 0){
			crop_height = photo.height;
		}		
		//dbg([crop_width, crop_height, crop_x, crop_y, image_zoom, zoom_scale])
		var CropData = {
			'print_width' : parseInt(t_w * 100)/100,
			'print_height' : parseInt(t_h * 100)/100,
			'crop_rotation' : 0,
			'crop_width' : parseInt(crop_width * image_zoom / zoom_scale),
			'crop_height' : parseInt(crop_height * image_zoom  / zoom_scale),
			'crop_x' : parseInt(crop_x * image_zoom / zoom_scale),
			'crop_y' : parseInt(crop_y * image_zoom / zoom_scale),
			'border_left' : parseInt(b_left / on_p.ppi * 100)/100,
			'border_top' : parseInt(b_top / on_p.ppi * 100)/100,
			'border_right' : parseInt(b_right / on_p.ppi * 100)/100,
			'border_bottom' : parseInt(b_bottom / on_p.ppi * 100)/100,
			'border_color' : "white",
			'type' : 'fixed_border', //(b_left <= 0 && b_top <=0 && b_right <=0 && b_bottom <= 0)?'crop_only':'fixed_border',
			'photo_orig_width' : photo.width,
			'photo_orig_height' : photo.height,
			'open_width' : CurrentMotion.open_width,
			'open_height' : CurrentMotion.open_height,
			'view_name' : [CurrentMotion.img_w_t, CurrentMotion.img_w_l, CurrentMotion.img_w, CurrentMotion.img_h].join("|")
			
		};
		

		var encStr = encodeCropStr(CropData);
		MainForm['photo_rendition'].value = encStr;
		//dbg(CurrentMotion);
		//dbg(CropData);
		//dbg(encStr);
		//decodeCropStr(encStr)
		//dbg(CurrentMotion);
	}
	
	function adjustImageMask()
	{
		var PADDING = 2; //some extra pickel issues
		var OFFSCR_PADD  =10;
		var clip_r = CurrentMotion.img_w;
		var clip_b = CurrentMotion.img_h;
		var clip_t = 0;
		var clip_l = 0;
		//make sure it is not off the canvas area
		if(CurrentMotion.img_w_l + CurrentMotion.img_w < CurrentMotion.canv_left + OFFSCR_PADD){
			CurrentMotion.img_w_l = CurrentMotion.canv_left - CurrentMotion.img_w + OFFSCR_PADD;
		}
		if(CurrentMotion.img_w_l > CurrentMotion.canv_left + CurrentMotion.canv_w - OFFSCR_PADD){
			CurrentMotion.img_w_l = CurrentMotion.canv_left + CurrentMotion.canv_w - OFFSCR_PADD;
		}
		if(CurrentMotion.img_w_t + CurrentMotion.img_h < CurrentMotion.canv_top + OFFSCR_PADD){
			CurrentMotion.img_w_t = CurrentMotion.canv_top - CurrentMotion.img_h + OFFSCR_PADD;
		}
		if(CurrentMotion.img_w_t > CurrentMotion.canv_top + CurrentMotion.canv_h - OFFSCR_PADD){
			CurrentMotion.img_w_t = CurrentMotion.canv_top + CurrentMotion.canv_h - OFFSCR_PADD;
		}
		
		if(clip_r + CurrentMotion.img_w_l > CurrentMotion.total_w){ 
			clip_r = CurrentMotion.total_w - CurrentMotion.img_w_l;
		}
		clip_l = CurrentMotion.img_w_l<0?clip_l-CurrentMotion.img_w_l:clip_l;
		if(clip_b + CurrentMotion.img_w_t > CurrentMotion.total_h){ 
			clip_b = CurrentMotion.total_h -  CurrentMotion.img_w_t;
		}
		clip_t = CurrentMotion.img_w_t<0?-CurrentMotion.img_w_t:clip_t;
		$s(MainImgWrap, 'top', CurrentMotion.img_w_t + 'px');
		$s(MainImgWrap, 'left', CurrentMotion.img_w_l + 'px');
		$s(MainImgWrap, 'height', CurrentMotion.img_h + 'px');
		$s(MainImgWrap, 'width', CurrentMotion.img_w  + 'px');
		$s(MainImgWrap, 'clip', 'rect(' + clip_t + 'px, ' + clip_r + 'px,' +  clip_b + 'px, ' + clip_l +'px)');

		$s(MainImg, 'height', CurrentMotion.img_h + 'px');
		$s(MainImg, 'width', CurrentMotion.img_w + 'px');
		
		$s(MainCanvas, 'top', CurrentMotion.canv_top + 'px');
		$s(MainCanvas, 'left', CurrentMotion.canv_left + 'px');
		$s(MainCanvas, 'height', CurrentMotion.canv_h + 'px');
		$s(MainCanvas, 'width', CurrentMotion.canv_w + 'px');
	}
	
	function adjustDimsForProd(prod, do_not_set)
	{
		prod = prod || CurrentProdId;
		if(!CurrentMitem){ return; }
		if(!giftData[prod]){ return; }
		var on_p = giftData[prod];
		var useImages = UseGiftImages || on_p;
		var t_h = on_p.height;
		var t_w = on_p.width;
		if(useImages.img_url){
			$s(MainGiftItemImg, 'display', 'inline');
			setImg(MainGiftItemImg, IMG_BASE_URL + useImages.img_url);
			$s(MainGiftItemImg, 'width', t_w + 'px');
			$s(MainGiftItemImg, 'height', t_h + 'px');
			$s(MainGiftItemWrap, 'width', t_w + 'px');
			$s(MainGiftItemWrap, 'height', t_h + 'px');
		}else{
			$s(MainGiftItemImg, 'display', 'none');
		}
		CurrentMotion.photo_orig_height = photo.height;
		CurrentMotion.photo_orig_width = photo.width;
		if(on_p.opening && !do_not_set){
			//fit image to 'height' of the current item top opening and center it
			var o_h = parseInt(useImages.opening.height);
			var img_w = parseInt(o_h * photo.asp);
			CurrentMotion.open_height = useImages.opening.height;
			CurrentMotion.open_width = parseInt(useImages.opening.width);
			
			var o_w = parseInt(useImages.opening.width);
			var img_top_off = parseInt(useImages.opening.yoff);
			var img_left = parseInt(t_w / 2 - img_w / 2);
			
			//sku dependant
			CurrentMotion.canv_top = img_top_off;
			CurrentMotion.canv_w = o_w;
			CurrentMotion.canv_left = parseInt(useImages.opening.xoff);
			CurrentMotion.canv_h = o_h;
			CurrentMotion.total_w = t_w;
			CurrentMotion.total_h = t_h;
			//if we've moved already, we DO NOT reset these
			if(!DidMove){
				CurrentMotion.img_w = img_w;
				CurrentMotion.img_h = o_h;
				CurrentMotion.img_w_t = img_top_off;
				CurrentMotion.img_w_l = img_left;
			}
			adjustImageMask();
		}
	}
	
	function tglMaskImageType(type, prod)
	{
		prod = prod || CurrentProdId;
		type = type || 'url';
		if(!giftData[prod]){ return; }
		var on_p = UseGiftImages || giftData[prod];
		if(on_p.img_url){
			setImg(MainGiftItemImg, IMG_BASE_URL + on_p.img_url);
		}
		if(type == 'mask' && on_p.img_mask_url){
			setImg(MainGiftItemImg, IMG_BASE_URL + on_p.img_mask_url);
		}
		if(type == 'mask'){
			$('ptpShowMaskTitle').innerHTML = ptpMaskHideMessage || 'Hide';
		}else{
			$('ptpShowMaskTitle').innerHTML = ptpMaskShowMessage || 'Show';
		}
	}
	
	function setChoices()
	{
		setAttributeSels();
		getProductId();
		stopMotion();
		tglMaskImageType($('ptpMaskTgl').checked?'url':'mask');
		if(onChange){ onChange(); }
	}
	
	function setFromProdId(pid)
	{
		var g = giftData[MainForm.prod.value || pid];
		if(!g){ return; }
		var got_master = false;
		var m_item = g.master_item_id;
		for(var i=0;i<MItemSel.options.length;i++){
			if(MItemSel.options[i].value == m_item){
				MItemSel.selectedIndex = i;
				got_master = m_item;
				break;
			}
		}
		if(!got_master){ return; }
		//set the attributes
		for(el in g.attributes){
			var o_a = g.attributes[el];
			var got_a = MainForm['att_' + el + '_' + m_item];
			if(!got_a){ continue; }
			if(got_a.tagName.toLowerCase() != 'select'){
				got_a.value = o_a[0];
			}else{
				for(var i=0;i<got_a.options.length;i++){
					if(got_a.options[i].value == o_a[0]){
						got_a.selectedIndex = i;
						break;
					}
				}
			}
		}
	}
									
	function tglModAdd(sel){
		var add = $('cprod_addbut');
		var mod = $('cprod_modbut');
		if(MainForm.orig_prod && MainForm.orig_prod.value != sel){
			$s(mod, 'display' , 'none');
			$s(add, 'display' , 'block');
		}else if(MainForm.orig_prod){
			$s(add, 'display' , 'none');
			$s(mod, 'display' , 'block');
		}
		
	}
	function isInt(v){
		if(!parseInt(v.value)){
			alert("Please enter a valid number");
			v.value = 1;
		}
	}
	function addQuantity(){
		q = $F(MainForm['ptpQtySelect']);
		if(q == 10){
			tglQuantity(-11);
			
		}else{
			MainForm['ptpQtySelect'].selectedIndex += 1;
		}
		if(onQuantityChange){ onQuantityChange(getQuantity()); }
		priceSw($F(MainForm['prod']));

	}
	
	function getPrice(sel, q){
		var o = giftData[sel];
		if(!o){ return {}; }
		q = q || getQuantity();
		var p = 0;
		if(q == 1){
			p = o.price_a[0];
		}else{
			var c = o.price_a[0].trim().charAt(0);
			vv =  parseFloat(o.price_v[0]);
			if(o.price_a.length > 1){
				vv += (q - 1) * parseFloat(o.price_v[1]);
			}else{
				vv = q * vv;
			}
			vv = Math.floor(vv * 100) / 100;
			vvstr = ("" + vv).split('.');
			p  = c + vvstr[0];
			if(vvstr[1] && vvstr[1].length == 1){
				p += "." + vvstr[1] + "0";
			}else if(vvstr[1]){
				p += "." + vvstr[1];
			}else{
				p += ".00";
			}
		}
		return {price : p, price_map:o };
	}
	
	function priceSw(sel, q){
		q = q || $F(MainForm['ptpQtySelect']);
		var oo = getPrice(sel, q);
		if(!oo){ return; }
		var o = oo['price_map'];
		$('priceDisplay').innerHTML = oo['price'];
		$('giftInfo').innerHTML = giftData[sel].help_text.replace('src="/', 'src="' + IMG_BASE_URL + "/");
		$('ptpOnPrice').innerHTML = oo['price'];
		var c_price = oo['price'];
		if(ptpOnPricePrefix){
			$('ptpOnPrice').innerHTML = ptpOnPricePrefix + $('ptpOnPrice').innerHTML;
		}
		if(ptpOnPricePostfix){
			$('ptpOnPrice').innerHTML = $('ptpOnPrice').innerHTML + ptpOnPricePostfix;
		}
		$('ptpPriceBreak').innerHTML = '';

		$('ptpPriceBreak').innerHTML = '';
		if(q == 1 && o.price_a.length >= 2){
			$('ptpPriceBreak').innerHTML = '<a href="#" onclick="PtpGifts.addQuantity();return false;">Add another for only ' + o.price_a[1] +'</a>';
		}
		tglModAdd(sel);
		return c_price;
	}
	
	function getQuantity(){
		var f = MainForm;
		var sel = $('ptpQtySelect');
		var inp = $('ptpQtyValue');
		if((!sel || $F(sel) < 0) && $F(inp)){
			$F.set(f.quantity, $F(inp));
		}else if(sel){
			$F.set(f.quantity, $F(sel));
		}else{
			$F.set(f.quantity, 1);
		}
		return $F(f.quantity);
	}

	function subJax(){
		var ff = $Connect.setForm(MainForm);
		function chk(o){
			var out = null;
			try {
				eval ("out = " + o.responseText);
				if(out.status != 'ok'){
					alert(out.message);
					return;
				}
				var info = out['info'];
				var l_item = info['last_item'];
				var prod = l_item['product'];
				if(out['message']){
					var msg = out['message'];
					msg += "\n - " + prod['description'];
					var pri =  l_item['format_price'];
					msg += "\n - " + l_item['quantity'] + " @ " + pri;
					alert(msg);
					if($('cprod_in_cart')){
						var msg = l_item['quantity'] + " Item Added";
						if(l_item['quantity'] > 1){
							msg = l_item['quantity'] + " Items Added";
						}
						if(info['total_quantity'] > 1){
							msg += " (" + info['total_quantity'] + " items in cart)";
						}
						$('cprod_in_cart').innerHTML = msg;
						show('cprod_go_to_cart');
					}
					if(MainForm['moding'] && l_item['key']){
						$F.set(MainForm['moding'], l_item['key']);
						tglModAdd();
					}
				}
				if(onSubmit){
					onSubmit(o);
				}
			} catch(e) {
				alert("Request Failed, sorry. " + e.toString())
				return;
			} 
		}
		PtpData.request(useAjax,
			{
				method: 'POST',
				parameters : ff + '&additive=0&js=1',
				onComplete: chk
			}
		);
	}
					
	function chkSubmit(forceadd){
		var f = MainForm;
		getQuantity();
		if(!didMotion && alertOnNoMotion){
			if(!alertOnNoMotion()){
				return false;
			}
		}
		if($F(f.quantity) > 0){
			if(forceadd && f['moding']){
				$F.set(f['moding'], '');
			}
			if(useAjax){
				return subJax();
			}
			f.submit()
		}
		return false;
	}
	function tglQuantity(v){
		var sel = $('ptpQtySelect');
		var inp = $('ptpQtyValue');
		if(v < 0){
			$s(inp, 'display' , 'inline');
			$s(sel, 'display' , 'none');
			inp.value = -parseInt(v);
		}else{
			$s(inp, 'display' , 'none');
			$s(sel, 'display' , 'inline');
		}
		if(onQuantityChange){ onQuantityChange(getQuantity()); }
	}
	
	return {
		'init': function(indata){
			init_data(indata);
			
			MainImg = $('giftOrigImage');
			MainImgWrap = $('giftImageLay');
			MainGiftItemWrap = $('giftItem');
			MainGiftItemImg = $('giftItemImg');
			//watch it
			PtpWatchImg.add(MainImg, MainImg.src);
			MainCanvas = $('giftItemCanvas');
			MainForm = document.gftform;
			MItemSel = MainForm.ptp_master_item_id;
			MItemAttrs = $C('ptpMasterItemAttrs');
			//if a prod in the slot ..use it
			if(MainForm.prod.value){
				setFromProdId(MainForm.prod.value);
			}else{

				for(var i=0,l=giftDataIdx.length; i<l; ++i){
					if(giftData[giftDataIdx[i]]['default']){
						setFromProdId(giftDataIdx[i]);
						break;
					}
				}
			}
			//if crop use it
			var got_rend = MainForm.photo_rendition.value;
			setChoices();
			if(got_rend){
				decodeCropStr(got_rend);
			}
			if(onFirstItemSelected){ onFirstItemSelected(); }
			
		},
		'tglGift' : function(){
			setChoices();
		},
		'setChoices' : function(){
			setChoices();
		},
		'dbg' : dbg,
		'getOn' : getOn,
		'getPrice' : getPrice,
		'getCurrent' : getOn,
		'addQuantity' : addQuantity,
		'updatePrice' : priceSw,
		'shiftUpDown' : shiftTB,
		'shiftLeftRight' : shiftLR,
		'shiftZoom' : shiftZoom,
		'stopMotion' : stopMotion,
		'tglMaskImageType': tglMaskImageType,
		'adjustAlert' : function(){
			alert("Please use the controls on the right to adjust the image.");
		 }, 
		'priceSw': priceSw,
		'tglModAdd' : tglModAdd,
		'tglQuantity' : tglQuantity,
		'isInt' : isInt,
		'chkSubmit' : chkSubmit
	}
}();

