var startLeft, startTop, startPhotoLeft, startPhotoTop, startBackLeft, startBackTopl
var partsDragging=false, photoDragging=false;
var selectedItem=null, selectedContainer=null, selectPhoto=false, selectText=false;
var zoomSlider, rotateSlider, prevUploadedFile=null;
var swfu;
var font_size_part = 19;

var Prof = {
	common: {
		isMSIE: /*@cc_on!@*/false,
		isIE6: function(){
			var arVersion = navigator.appVersion.split("MSIE");
	        var version = parseFloat(arVersion[1]);
	        if(version < 7 ) {
	            return true;
	        }
	        return false;
		},
		mode: {
			current: 1,
			change: function(number, eraseFrame) {
				this.current = number;

				var regex = new RegExp('input_mode_'+number);
			    var input_mode_containers = $$('.input_mode');
			    input_mode_containers.each(function(el){
			    	if (el.className.match(regex)) {
			    		el.setStyle({'display': 'block'});
			    	}
			    	else {
                        el.setStyle({'display': 'none'});
			    	}
			    });

			    var mode_control_containers = $$('.mode_control');
			    mode_control_containers.each(function(el){
			        el.setStyle({'display': 'none'});
			    });
			    $('mode_control_'+number).setStyle({'display': 'block'});
			    selectFramePage(0);

			    Prof.text._diff = {};
			    Prof.text.clear(selectedContainer-1);

			    var frame = $$('.activeFrame')[0];
			    if (frame && eraseFrame) {
			        frame.setStyle({
			            'background': '',
			            'filter': ''
			        });
			    } else {
			    	frame.setStyle({'background': 'url("'+BASE_DIR+'img/prof/frame/edit/201102/001.png") top left no-repeat'});
			    	frame.setAttribute('rel', BASE_DIR+'img/prof/frame/edit/201102/001.png');
			    }

			    var c = $A(document.select_photo_form.select_photo).find(function(v) {
                    v.checked = null;
                    return v.value = 1;
                });
                if (c) c.checked = 'checked';
			},
			change_confirm: function(number) {
                switch(number) {
			        case 1:
			          Modalbox.show($('switchModeConfirm_1'), {title: 'テキスト入力を切り替えます', width: 350, overlayOpacity: 0.4});
			          break;
			        case 2:
			          Modalbox.show($('switchModeConfirm_2'), {title: 'テキスト入力を切り替えます', width: 350, overlayOpacity: 0.4});
			          break;
			        case 3:
                      Modalbox.show($('switchModeConfirm_3'), {title: 'テキスト入力を切り替えます', width: 350, overlayOpacity: 0.4});
                      break;
			    }
			}
		}
	},
	text: {
        margin: {'left':24,'top':64},
        default_position: {'left':168,'top':81},
        max_position: {'left':0,'top':43,'right':452,'bottom':207},
        max_line_feed: {prof_input_4: 3, prof_input_5: 6, prof_input_6: 6},
        line_feed: /*@cc_on!@*/false ? '\r\n' : '\n',
        default_color: '000000',
        _diff:{},
        _commited:[{mode:1},{mode:1}],
        timer:{
            line_feed:null
        },
        onload: function() {
        	var ref = this;

        	var colorpicker_init = false;
        	Control.ColorPicker.prototype.updateSwatch = function(){
        		if (!colorpicker_init) {
        			Event.observe('color_select_other', "click", this.toggleOnClickListener);
        			colorpicker_init = true;
        		}
        		var rgb = YAHOO.util.Color.hex2rgb( this.field.value );
        	    if (!YAHOO.util.Color.isValidRGB(rgb)) return;
        	    this.swatch.style.backgroundColor = "rgb(" + rgb[0] + ", " + rgb[1] + ", " + rgb[2] + ")";
        	    var hsv = YAHOO.util.Color.rgb2hsv( rgb[0], rgb[1], rgb[2] );
        	    for(var i=0;i<hsv.length;i++) {
        	    	if (!hsv[i]) hsv[i] = 0; 
        	    }
        	    this.swatch.style.color = (hsv[2] > 0.65) ? "#000000" : "#FFFFFF";
        	};
        	Control.ColorPicker.prototype.updateFromFieldValue = function(event) {
        	    if (!this.isOpen) return;
        	    var field = (event && Event.findElement(event, "input")) || this.field;
        	    var rgb = YAHOO.util.Color.hex2rgb( field.value );
        	    if (!YAHOO.util.Color.isValidRGB(rgb)) return;
        	    var hsv = YAHOO.util.Color.rgb2hsv( rgb[0], rgb[1], rgb[2] );
        	    for(var i=0;i<hsv.length;i++) {
        	    	if (!hsv[i]) hsv[i] = 0; 
        	    }
        	    this.control.selector.style.left = Math.round(hsv[1] * this.control.pickerArea.offsetWidth) + "px";
        	    this.control.selector.style.top = Math.round((1 - hsv[2]) * this.control.pickerArea.offsetWidth) + "px";
        	    this.control.hueSlider.setValue((1 - hsv[0]));
            };
        	
        	var colorpicker_callback = function() {
        		setTimeout(function(){
	        		var c = $$('.color_select').find(function(el){
			            el.checked = null;
			            return (el.id == 'color_select_other');
			        });
	    			c.checked = 'checked';
        		}, 100);
        	}
        	var colorpicker = new Control.ColorPicker('color_select_other', {
        		IMAGE_BASE : BASE_DIR+'img/prof/edit/picker/',
        		'swatch'   : 'color_select_other_sample',
        		'onOpen'   : colorpicker_callback,
        		'onUpdate' : colorpicker_callback
        	});
        	
        	var color_selects = $$('.color_select').findAll(function(el){
        		return (el.id != 'color_select_other');
        	});
        	color_selects.each(function(el){
        		Event.observe(el, 'click', function(event) {
        			if (colorpicker.isOpen) colorpicker.close();
        		});
        	});
        	
        	
        	$$('.preview_text_container').each(function(co){
        		co.show_border = function() {
        			var left = parseInt(this.getStyle('left').replace(/px$/, ''));
	                var top = parseInt(this.getStyle('top').replace(/px$/, ''));
	                this.setStyle({
	                	'border':'1px solid #00f',
	                	'top':top-1+'px',
	                	'left':left-1+'px'
	                });
        		};
        		
        		co.hide_border = function() {
        			var left = parseInt(this.getStyle('left').replace(/px$/, ''));
	                var top = parseInt(this.getStyle('top').replace(/px$/, ''));
	                this.setStyle({
	                	'border':'',
	                	'top':top+1+'px',
	                	'left':left+1+'px'
	                });
        		};
        		

        		Event.observe(co, 'click', function(event) {
        			Prof.photo.clear_border_all();
                    selectPhoto = false;
        			
        			selectText = co;
        			$('palletControllerDisabler').hide();
        			co.show_border();
        			
        			var size = 0;
        			if ($('font_size').value) {
        				size = selectText.slider_val;
        			}
        			zoomSlider.setValue(size);
                    $('zoom_level').style.display = 'none';
                    $('font_size').style.display = 'block';
        		});
        		
		        new Draggable(co, {
		            'onStart': function(d, e) {
		                partsDragging = true;
		                var el = d.element;
		                startPhotoLeft = el.getStyle('left')+22;
		                startPhotoTop = el.getStyle('top')+22;

		                var left = parseInt(co.getStyle('left').replace(/px$/, ''));
		                var top = parseInt(co.getStyle('top').replace(/px$/, ''));
		                co.show_border();

		                startBackLeft = left;
		                startBackTop = top;
		            },
		            'onEnd': function(d, e) {
		                co.hide_border();
		            },
		            'onDrag': function(d, e) {
		            },
		            'starteffect': null,
		            'endeffect': null,
		            'ghosting': false,
		            'snap': function(x, y) {
		                if (x > ref.max_position.right) {
		                    x = ref.max_position.right;
		                }
		                else if (x < ref.max_position.left) {
		                    x = ref.max_position.left;
		                }
		                if (y > ref.max_position.bottom) {
		                    y = ref.max_position.bottom;
		                }
		                else if (y < ref.max_position.top) {
		                    y = ref.max_position.top;
		                }
		                return [x,y];
		            }
		        });
		    });

        	setInterval(function() {
        		var style = $('color_select_other').checked ? {'display': 'none'} : {'display': ''};
        		$('color_select_other_sample_image').setStyle(style);
        	}, 500);
        	
		    this.timer.diff = setInterval(function() {
                var blank = true;
                $$('.textData').each(function(el) {
                   if (el.value) {
                       blank = false;
                   }
                   else if (ref.diff(el.name)) {
                       blank = false;
                   }
                });
                if (blank) return;

                var diff = false;
                $$('.text').each(function(el) {
                    if (!ref.diff(el.name)) ref.diff(el.name, '');
                    if (ref.diff(el.name) != el.value) {
                        diff = true;
                        ref.diff(el.name, el.value);
                    }

                });

                var r = $A(document.color_select_form.color_select).find(function(v) {
                    return v.checked;
                });
                if (!r) return;
                
                if (!ref.diff('color_select')) {
                    ref.diff('color_select', '');
                }
                if (ref.diff('color_select') != r.value) {
                   diff = true;
                   ref.diff('color_select', r.value);
                }

                if (diff) {
                    ref.preview();
                }
            }, 3000);

		    for (var i=1;i<=2;i++) {
		    	var c = this.commit_all(i-1);
		        var t = c['top'] ? parseInt(c['top'])+this.margin.top : this.default_position.top;
		        var l = c['left'] ? parseInt(c['left'])+this.margin.left : this.default_position.left;
		        $('preview_text_container_'+i).style.left = l+'px';
		        $('preview_text_container_'+i).style.top = t+'px';

		        if (i==1) {
		            $('previous_text').style.left = l+'px';
		            $('previous_text').style.top = t+'px';
		        }
		    }

		    $$('.textArea').each(function(element){
		        Event.observe(element, 'focus', function(e){
		        	if (ref.timer.line_feed) return;

		            var el = Event.element(e);
		            ref.timer['line_feed_'+el.id] = setInterval(function(){
		                var lf = el.value.match(new RegExp(ref.line_feed, 'g'));
		                if (!lf || lf.length < ref.max_line_feed[el.id]) return;

		                var arr = el.value.split(ref.line_feed);
		                var text = '';
		                var max = ref.max_line_feed[el.id];
		                if (arr[arr.length-1] == '') {
		                    text = el.value.replace(new RegExp('('+ref.line_feed+'.?)$'), '');
		                }
		                else {
		                    for(var i=0; i<max; i++) {
		                        if (arr[i] == '') {
		                            max++;
		                            continue;
		                        }
		                        if (arr[i] == undefined) break;
		                        text += arr[i];
		                        if (i+1 != max) {
		                            text += ref.line_feed;
		                        }
		                    }
		                }
		                el.value = text;
		            },100 );
		        });
		        Event.observe(element, 'blur', function(e) {
		        	var el = Event.element(e);
                    clearInterval(ref.timer['line_feed_'+el.id]);
                });
		    });

		    $$('#tab_navigation .active_button').each(function(element){
			    Event.observe(element, 'click', function(e) {
			    	var el = Event.element(e);
			    	var num = el.className.match(/button_mode_(.{1})/);
			    	Prof.common.mode.change_confirm(parseInt(RegExp.$1));
			    });
		    });
        },
        diff: function(key, val) {
        	if (val != undefined) {
        	   this._diff[key] = val;
        	}
        	else {
        	   return this._diff[key];
        	}
        },
        commit_all: function(id, obj){
        	if (obj != undefined) {
        	   this._commited[id] = obj;
        	}
        	else {
        		return this._commited[id];
        	}
        },
        commit: function(id, key, value) {
        	if (value != undefined) {
               this._commited[id][key] = value;
            }
            else {
                return this._commited[id][key];
            }
        },
        is_modified: function(id) {
        	var diff = false;
		    var commited_obj = this.commit_all(id);
		    for(var i in this._diff) {
		        for(var j in commited_obj) {
		            if (i != j) continue;
		            if (this._diff[i] != commited_obj[j]) {
		                diff = true;
		                break;
		            }
		        }
		        if (diff) break;
		    }
		    return diff;
        },
        save: function() {
        	var c = this.commit_all(selectedContainer-1);
		    for(var i in this._diff) {
		        c[i] = this._diff[i];
		    }
		    this.commit_all(selectedContainer-1, c);
        },
        preview: function() {
		    var container = $('preview_text_container_'+selectedContainer);
		    container.removeClassName('activeText');
		    container.removeClassName('loaded');

		    if ($('font_select').value) {
		        $('font').value = $('font_select').value;
		    }
		    if ($('font_size').value) {
		    	$('size').value = $('font_size').value.replace(/px$/, '');
		    }
		    $('color').value = this.diff('color_select') ? this.diff('color_select') : this.default_color;
		    $('mode').value = Prof.common.mode.current;
		    
		    var arg = Form.serialize('text_form');
		    var ref = this;
		    new Ajax.Request(
		        BASE_DIR + 'Image/set_text/' + selectedContainer + '/',
		        {
		            method: 'post',
		            parameters: arg,
		            onComplete: function(originalRequest, response_value) {
		                var img = document.createElement('img');

		                if (Prof.common.isIE6()) {
		                   img.src = BASE_DIR+'Image/text_preview/'+selectedContainer+'/1/'+new Date().getTime();
		                }
		                else {
		                   img.src = BASE_DIR+'Image/text_preview/'+selectedContainer+'/0/'+new Date().getTime();
		                }
		                img.style.cursor = 'pointer';

		                container.innerHTML = '';
		                container.appendChild(img);
		                container.addClassName('activeText');

		                if (originalRequest.responseText) {

		                    container.addClassName('loaded');
		                    container.setStyle({
		                    	'display': 'block',
		                        'z-index': '1003'
		                    });
		                    //ref.resize_container(container);
		                }
		                else {
		                	container.setStyle({
		                		'display': 'none',
		                		'z-index': '0',
		                		'top'    : ref.default_position.top+'px',
		                		'left'   : ref.default_position.left+'px'
		                    });
		                }
		            }
		        }
		    );
        },
        clear: function (id) {
		    var commited_obj = this.commit_all(id);
		    $$('.textData').each(function(el) {
		        if (!commited_obj[el.name]) commited_obj[el.name] = '';
		        el.value = commited_obj[el.name];
		    });

		    if (commited_obj['color_select']) {
		        var c = $$('.color_select').find(function(el){
		            el.checked = null;
		            return (commited_obj['color_select'] == el.value);
		        });
		        if (c) {
		        	c.checked = 'checked';
		        }
		        else {
		        	$('color_select_other').value = commited_obj['color_select'];
		        	$('color_select_other_sample').style.backgroundColor = '#'+commited_obj['color_select'];
		        	$('color_select_other').checked = 'checked';
		        }
		    }
		    else {
		    	var default_color = this.default_color;
		        var c = $$('.color_select').find(function(el){
		            el.checked = null;
		            return (el.value == default_color);
		        });
		        if (c) c.checked = 'checked';
		    }

		    if (commited_obj['font_select']) {
		        var c = $A($('font_select').options).find(function(el){
		            el.selected = null;
		            return (commited_obj['font_select'] == el.value);
		        });
		        if (c) c.selected = 'selected';
		    }
		    else {
		        var c = $A($('font_select').options).find(function(el){
		            el.selected = null;
		            return (el.value == 1);
		        });
		        if (c) c.selected = 'selected';
		    }

		    text = $$('.activeText')[0];
		    if (text) {
		        text.removeClassName('loaded');
		        this.preview();
		    }
		},
		resize_container: function(c) {
			var width = 253;
			var height = 108;

			if (Prof.common.mode.current != 1) {
				var len = 0;
	            $$('.textData').each(function(el) {
	                var tmp = el.value.split(ref.line_feed);
	                height = tmp.length * 18;
	                for(var i=0;i<tmp.length; i++) {
	                	if (tmp[i].length > len) {
	                		len = tmp[i].length;
	                	}
	                }
	            });

	            if (len > 0) {
	            	width = len * 14;
	            }
			}
            c.setStyle({
            	'width':width+'px',
            	'height':height+'px'
            });
		}
    },
    photo: {
    	onload: function(){
    		var ref = this;
    		$A(document.select_photo_form.select_photo).each(function(el) {
                Event.observe(el, 'click', function(){
                    ref.clear_border_all();
                });
            });
    	},
    	get_active_id: function(id) {
    		if (!id) {
    			id = selectedContainer ? selectedContainer : 1;
    		}
            var r = $A(document.select_photo_form.select_photo).find(function(v) {
                return v.checked;
            });
            if (r) {
                id += '_'+r.value;
            }
            else {
            	id += '_1';
            }
            return id;
    	},
        get_active: function() {
        	return $('photo_'+this.get_active_id());
        },
        get_active_all: function(id) {
        	if (!id) id = selectedContainer ? selectedContainer : 1;
        	var photos = [];
        	photos.push($('photo_'+id+'_1'));
            photos.push($('photo_'+id+'_2'));
        	return photos;
        },
        add_class_all: function(classname, id){
        	if (!id) id = selectedContainer ? selectedContainer : 1;
        	$('photo_'+id+'_1').addClassName(classname);
        	$('photo_'+id+'_2').addClassName(classname);
        },
        remove_class_all: function(classname, id) {
        	if (!id) id = selectedContainer ? selectedContainer : 1;
            $('photo_'+id+'_1').removeClassName(classname);
            $('photo_'+id+'_2').removeClassName(classname);
        },
        clear_border_all: function() {
        	$A(this.get_active_all()).each(function(el){
        		if (el.getStyle('border')) {
        			var left = parseInt(el.getStyle('left').replace(/px$/, ''));
                    var top = parseInt(el.getStyle('top').replace(/px$/, ''));
	    		    el.setStyle({
	                    'border':'',
	                    'left':left+1+'px',
	                    'top':top+1+'px'
	                });
        		}
        	})
        },
        show_border: function(){
        	var el = this.get_active();
        	if (!el.getStyle('border')) {
                var left = parseInt(el.getStyle('left').replace(/px$/, ''));
                var top = parseInt(el.getStyle('top').replace(/px$/, ''));
                el.setStyle({
                    'border':'1px solid #f00',
                    'left':left-1+'px',
                    'top':top-1+'px'
                });
            }
        },
        get_clicked: function(event) {

        	var x = Event.pointerX(event)-11;
	        var y = Event.pointerY(event)-11;

	        var active =  $A(this.get_active_all().reverse()).find(function(p){
	            var xok = false;
		        var yok = false;
		        var left = p.style.left ? parseInt(p.style.left.replace(/px$/, '')) : 22;
	            var top = p.style.top  ? parseInt(p.style.top.replace(/px$/, '')) : 68 ;
	            var width = parseInt(p.style.width.replace(/px$/, ''));
	            var height = parseInt(p.style.height.replace(/px$/, ''));
	            if (x > left && x < left+width) {
	                xok = true;
	            }
	            if (y > top && y < top+height) {
	                yok = true;
	            }
	            if (xok && yok) {
	               p.id.match(/(.{1})$/);
	               var number = RegExp.$1;
	               var r = $A(document.select_photo_form.select_photo).find(function(v) {
		              return v.value == number;
		           });
		           r.checked = 'checked';
	            }
	            return (xok && yok);
	        });

            return active ? active : this.get_active();
        },
        thumb_add_class_all: function(classname, id){
            if (!id) id = selectedContainer ? selectedContainer : 1;
            $('photo_thumb_'+id+'_1').addClassName(classname);
            $('photo_thumb_'+id+'_2').addClassName(classname);
        },
        thumb_remove_class_all: function(classname, id) {
            if (!id) id = selectedContainer ? selectedContainer : 1;
            $('photo_thumb_'+id+'_1').removeClassName(classname);
            $('photo_thumb_'+id+'_2').removeClassName(classname);
        },
        get_active_thumb_all: function(id) {
        	if (!id) id = selectedContainer ? selectedContainer : 1;
        	return [$('photo_thumb_'+id+'_1'), $('photo_thumb_'+id+'_2')];
        }
    }
};

function rotatePhoto(val) {
    $('editor').addClassName('photo_loading');

    var activePhoto = Prof.photo.get_active();//$('photo_'+selectedContainer);
    var angle = parseInt(activePhoto.getAttribute('angle')) + val;

    activePhoto.hide();;
    activePhoto.src = BASE_DIR + 'Image/rotate/' + Prof.photo.get_active_id() + '/' + angle;
    activePhoto.setAttribute('angle', angle);

    var base_width = activePhoto.getAttribute('base_width');
    var base_height = activePhoto.getAttribute('base_height');

    activePhoto.setAttribute('base_width', base_height);
    activePhoto.setAttribute('base_height', base_width);

    var width = activePhoto.getStyle('width');
    var height = activePhoto.getStyle('height');

    activePhoto.setStyle({'width': height, 'height': width});

    Event.observe(activePhoto, 'load', onLoadRotatePhoto);
}

function onLoadRotatePhoto(ev) {
    var activePhoto = Event.element(ev);
    if(!activePhoto.parentNode) {
        activePhoto = this;
    }
    activePhoto.show();
    $('editor').removeClassName('photo_loading');
    Event.stopObserving(activePhoto, 'load', onLoadRotatePhoto);
}

function uploadFile(el) {
    var activePhoto = Prof.photo.get_active();//$('photo_'+selectedContainer);

    activePhoto.setStyle({'display': 'none'});
    $('editor').addClassName('photo_loading');

    el.form.action = BASE_DIR + 'Image/upload/' + Prof.photo.get_active_id();
    el.form.submit();
}

function onUploadFile(id, width, height, hash) {
    var photo = $('photo_'+id);
    photo.src = BASE_DIR + 'Image/photo/' + id + '/' + hash;

    var thumb = $('photo_thumb_'+id);
    thumb.src = BASE_DIR + 'Image/preview_photo/' + id + '/40/30/' + hash;
    thumb.setStyle({'display':''});

    width = Math.floor(width * 0.46);
    height = Math.floor(height * 0.46);
    photo.setStyle({
        'width': width + 'px',
        'height': height + 'px'
    });

    photo.setAttribute('base_width', width);
    photo.setAttribute('base_height', height);
    photo.setAttribute('angle', '0');

    Event.observe(photo, 'load', onLoadUploadFile);
}

function onLoadUploadFile(ev) {
    var activePhoto = Event.element(ev);
    if(!activePhoto.parentNode) {
        activePhoto = this;
    }

    activePhoto.setStyle({'display': ''});
    $('editor').removeClassName('photo_loading');
    Event.stopObserving(activePhoto, 'load', onLoadUploadFile);
}

function selectFramePage(page) {

    var pagers = $$('#framePager img');
    for(var i=0;i<pagers.length;i++) {
        if(page == i) {
        	pagers[i].src = BASE_DIR + 'img/prof/edit/fram' + (i+1) + '_on.gif';
        }else{
            pagers[i].src = BASE_DIR + 'img/prof/edit/fram' + (i+1) + '.gif';
        }
    }

    var pages = $$('#palletFrames .framePages');
    for(var i=0;i<pages.length;i++) {
        if(page == i) {
            pages[i].show();
        }else{
            pages[i].hide();
        }
    }
    
    if ($('frameSelector')) {
	    var c = $A($('frameSelector').options).find(function(el){
	        el.selected = null;
	        return (page == el.value);
	    });
	    if (c) c.selected = 'selected';
    }
}

function savePreviousEditor(doPreview) {
    var id = selectedContainer;

    var photos = Prof.photo.get_active_all();
    var frame = $('frame_'+id);
    var parts = $('parts_'+id);
    var text = $('preview_text_container_'+id);

    var p_frame = $('previous_frame');
    var p_parts = $('previous_parts');
    var p_text  = $('previous_text');

    $A(photos).each(function(photo){
    	var number = photo.id.slice(-1);
    	var p_photo = $('previous_photo_'+number);
    	if (p_photo) {
            p_photo.src = photo.src;
		    p_photo.setAttribute('base_width', photo.getAttribute('base_width'));
		    p_photo.setAttribute('base_height', photo.getAttribute('base_height'));
		    p_photo.setAttribute('angle', photo.getAttribute('angle'));

		    p_photo.style.width = photo.style.width;
		    p_photo.style.height = photo.style.height;
		    p_photo.style.top = photo.style.top;
		    p_photo.style.left = photo.style.left;
    	}
    });
    $A(Prof.photo.get_active_thumb_all()).each(function(thumb){
    	var number = thumb.id.slice(-1);
    	var p_thumb = $('previous_thumb_'+number);
    	if (p_thumb) {
    		p_thumb.src = thumb.src;
    	}
    })

    p_frame.setAttribute('rel', frame.getAttribute('rel'));
    p_frame.style.background = frame.style.background;

    p_text.style.top = text.style.top;
    p_text.style.left = text.style.left;

    if (Prof.common.mode.current) {
    	Prof.text.commit(id-1, 'mode', Prof.common.mode.current);
    }
    if(doPreview) {
    	Prof.text.save();
        preview(id, photos, frame, parts, text);
    }
}

function preview(id, activePhoto, activeFrame, activeParts, activeText) {
    var preview = $$('#container_'+id+' .preview')[0];
    preview.setStyle({'background': 'url("'+BASE_DIR+'img/loading.gif") 119px 28px no-repeat'});

    var form = $('previewForm');
    form.innerHTML = '';

    var left = parseInt($('photoController').getStyle('left').replace(/px$/, ''))+22;
    var top = parseInt($('photoController').getStyle('top').replace(/px$/, ''))+22;

    if(activeFrame.getAttribute('rel')) {
        var path = activeFrame.getAttribute('rel').split('/').reverse();
        var file = path[3]+'/print/'+path[1]+'/'+path[0];
        form.appendChild(createInputHidden('data[frame]', file));
    }

    if (!(activePhoto instanceof Array)) {
    	activePhoto = [activePhoto];
    }

    for(var i=0;i<activePhoto.length;i++) {
    	var photo = activePhoto[i];
    	var key = 'data[photo_'+photo.id.slice(-1)+']';

	    form.appendChild(createInputHidden(key+'[angle]', photo.getAttribute('angle')));
	    if(photo.getStyle('width')) {
	        form.appendChild(createInputHidden(key+'[width]', photo.getStyle('width').replace(/px$/, '')));
	    }
	    if(photo.getStyle('height')) {
	        form.appendChild(createInputHidden(key+'[height]', photo.getStyle('height').replace(/px$/, '')));
	    }
	    form.appendChild(createInputHidden(key+'[left]', left - parseInt(photo.getStyle('left').replace(/px$/, ''))));
	    form.appendChild(createInputHidden(key+'[top]', top - parseInt(photo.getStyle('top').replace(/px$/, ''))));
    }

    form.appendChild(createInputHidden('data[text][left]', parseInt(activeText.getStyle('left').replace(/px$/, ''))-Prof.text.margin.left));
    form.appendChild(createInputHidden('data[text][top]', parseInt(activeText.getStyle('top').replace(/px$/, ''))-Prof.text.margin.top));
    form.appendChild(createInputHidden('data[mode]', Prof.common.mode.current));
    form.action = BASE_DIR + 'Image/preview/' + id;
    form.submit();
}

function previewImage(id, hash) {
    var preview = $$('#container_'+id+' .preview')[0];
    preview.setStyle({'background': 'url("'+BASE_DIR+'Image/previewImage/'+id+'/270/88/'+hash+'") 0px 0px no-repeat'});
}

function createInputHidden(name, value) {
    var element = document.createElement('input');
    element.setAttribute('type', 'hidden');
    element.setAttribute('name', name);
    element.setAttribute('value', value);
    return element;
}

function restorePreviousEditor(doSwitchMode) {
    var id = selectedContainer;

    var photos = Prof.photo.get_active_all(id);
    var frame = $('frame_'+id);
    var parts = $('parts_'+id);
    var text = $('preview_text_container_'+id);

    var p_frame = $('previous_frame');
    var p_parts = $('previous_parts');
    var p_text = $('previous_text');

    $A(photos).each(function(photo){
    	var number = photo.id.slice(-1);
        var p_photo = $('previous_photo_'+number);
        if (p_photo) {
            photo.src = p_photo.src;
		    photo.setAttribute('base_width', p_photo.getAttribute('base_width'));
		    photo.setAttribute('base_height', p_photo.getAttribute('base_height'));
		    photo.setAttribute('angle', p_photo.getAttribute('angle'));

		    photo.style.width = p_photo.style.width;
		    photo.style.height = p_photo.style.height;
		    photo.style.top = p_photo.style.top;
		    photo.style.left = p_photo.style.left;
        }
    });

    $A(Prof.photo.get_active_thumb_all(id)).each(function(thumb){
        var number = thumb.id.slice(-1);
        var p_thumb = $('previous_thumb_'+number);
        if (p_thumb) {
            thumb.src = p_thumb.src;
        }
    })

    frame.setAttribute('rel', p_frame.getAttribute('rel'));
    frame.style.background = p_frame.style.background;

    text.style.top = p_text.style.top;
    text.style.left = p_text.style.left;

    if (doSwitchMode) {
        Prof.common.mode.change(Prof.text.commit(id-1, 'mode'));
    }
}

function checkPreviousEditor() {
    var id = selectedContainer;

    var photos = Prof.photo.get_active_all(id);
    var frame = $('frame_'+id);
    var parts = $('parts_'+id);
    var text = $('preview_text_container_'+id);

    var p_frame = $('previous_frame');
    var p_parts = $('previous_parts');
    var p_text = $('previous_text');

    var modified = false;

    $A(photos).each(function(photo){
        var number = photo.id.slice(-1);
        var p_photo = $('previous_photo_'+number);
        if (p_photo) {
            modified |= photo.src != p_photo.src;
		    modified |= photo.base_width != p_photo.base_width;
		    modified |= photo.base_height != p_photo.base_height;
		    modified |= photo.angle != p_photo.angle;
		    modified |= photo.style.width != p_photo.style.width;
		    modified |= photo.style.height != p_photo.style.height;
		    modified |= photo.style.top != p_photo.style.top;
		    modified |= photo.style.left != p_photo.style.left;
        }
    });

    if(!frame.getAttribute('rel') || frame.getAttribute('rel') == 'null') {
        frame.setAttribute('rel', '');
    }
    if(!p_frame.getAttribute('rel') || p_frame.getAttribute('rel') == 'null') {
        p_frame.setAttribute('rel', '');
    }
    modified |= frame.getAttribute('rel') != p_frame.getAttribute('rel');

    modified |= parts.childNodes.length != p_parts.childNodes.length;

    if(!modified) {
        for(var i=0;i<parts.childNodes.length;i++) {
            if(!parts.childNodes[i].getAttribute('rel') || parts.childNodes[i].getAttribute('rel') == 'null') {
                parts.childNodes[i].setAttribute('rel', '');
            }
            if(!p_parts.childNodes[i].getAttribute('rel') || p_parts.childNodes[i].getAttribute('rel') == 'null') {
                p_parts.childNodes[i].setAttribute('rel', '');
            }
            modified |= parts.childNodes[i].src != p_parts.childNodes[i].src;
            modified |= parts.childNodes[i].rel != p_parts.childNodes[i].rel;
            modified |= parts.childNodes[i].getStyle('width') != p_parts.childNodes[i].getStyle('width');
            modified |= parts.childNodes[i].getStyle('height') != p_parts.childNodes[i].getStyle('height');
            modified |= parts.childNodes[i].getStyle('left') != p_parts.childNodes[i].getStyle('left');
            modified |= parts.childNodes[i].getStyle('top') != p_parts.childNodes[i].getStyle('top');
            if(modified) {
                return modified;
            }
        }
    }
    modified |= text.style.top != p_text.style.top;
    modified |= text.style.left != p_text.style.left;
    modified |= Prof.text.is_modified(id-1);

    return modified;
}

function selectContainer(container) {
    if(selectedContainer && selectedContainer != container && checkPreviousEditor()) {
        $('changeContainerId').value = container;
        Modalbox.show($('changeContainerConfirm'), {title: '選択中の画像は変更されています', width: 350, overlayOpacity: 0.4});
    }else{
        changeContainer(container);
    }
}
function changeContainer(container, status) {
    if(status != undefined) {
        Modalbox.hide();
    }
    if(status == 0) {
        savePreviousEditor(true);
    }
    if(status == 2) {
        return false;
    }
    if(selectedContainer != container) {
        if(selectedItem) {
            selectedItem.removeClassName('selectedItem');
            selectedItem.setStyle({ 'left': parseInt(selectedItem.getStyle('left').replace(/px$/, '')) + 1 + 'px' });
            selectedItem.setStyle({ 'top': parseInt(selectedItem.getStyle('top').replace(/px$/, '')) + 1 + 'px' });
            selectedItem = null;
        }

        $('palletControllerDisabler').show();
        $('palletRotatorDisabler').show();
        if(selectedContainer) {
        	Prof.photo.remove_class_all('activePhoto');

            $('frame_'+selectedContainer).removeClassName('activeFrame');
            $('parts_'+selectedContainer).removeClassName('activeParts');
            $$('.select_photo').each(
                function(el) {
                    el.style.display = 'none';
                }
            );
            selectPhoto = false;

            $('container_' + selectedContainer).removeClassName('activeContainer');
            restorePreviousEditor();
        }
        Prof.photo.add_class_all('activePhoto', container);
        $('frame_'+container).addClassName('activeFrame');
        $('parts_'+container).addClassName('activeParts');

        var uploaderForm = $('uploader_file').parentNode;
        uploaderForm.removeChild($('uploader_file'));
        var input_file = document.createElement('input');
        input_file.id = 'uploader_file';
        input_file.setAttribute('type', 'file');
        input_file.setAttribute('name', 'photo_' + Math.random());
        input_file.setAttribute('size', '30');
        Event.observe(input_file, 'change',
            function(ev) {
                uploadFile(Event.element(ev));
            }
        );
        uploaderForm.appendChild(input_file);

        $('container_' + container).addClassName('activeContainer');

        if (selectedContainer) {
            var text = $('preview_text_container_'+selectedContainer);
            text.removeClassName('activeText');
            text.setStyle({'display':'none'});
            Prof.photo.thumb_add_class_all('photo_thumb_disable', selectedContainer);
        }
        var a_text = $('preview_text_container_'+container);
        a_text.addClassName('activeText');
        Prof.photo.thumb_remove_class_all('photo_thumb_disable', container);

        selectedContainer = container;
        Prof.common.mode.change(Prof.text.commit(selectedContainer-1, 'mode'));
        savePreviousEditor(false);
    }
}

function confirmContinueNext(url) {
    var blankCount = 0;
    for(var i=0;i<2;i++) {
        if(checkBlank(i+1)) {
            blankCount++;
        }
    }

    if(blankCount == 2) {
        Modalbox.show($('isAllBlankAlert'), {title: '画像が1つも編集されていません', width: 350, overlayOpacity: 0.4});
        return true;
    }
    if(blankCount == 1) {
        Modalbox.show($('blankContinueConfirm'), {title: '１つの画像しか編集されていません', width: 350, overlayOpacity: 0.4});
        return true;
    }

    if(selectedContainer && checkPreviousEditor()) {
        Modalbox.show($('unsaveContinueConfirm'), {title: '選択中の画像は変更されています', width: 350, overlayOpacity: 0.4});
    }else{
    	window.parent.location.href = url + '/' + RESTORE_NO;
    }
    return true;
}

function continueNext(status, url) {
    if(status == 0) {
        var photos = Prof.photo.get_active_all();
        var frame = $('frame_'+selectedContainer);
        var parts = $('parts_'+selectedContainer);
        var text = $('preview_text_container_'+selectedContainer);

        Event.observe($('uploader_frame'), 'load', function() {
            window.parent.location.href = url + '/' + RESTORE_NO;
        });

        preview(selectedContainer, photos, frame, parts, text);
    }
    if(status == 1) {
        window.parent.location.href = url + '/' + RESTORE_NO;
    }
    if(status == 2) {
        Modalbox.hide();
    }
    if(status == 3) {
        var id = 0;
        for(var i=0;i<2;i++) {
            if(!checkBlank(i+1)) {
                id = i+1;
                break;
            }
        }
        var photo = Prof.photo.get_active_all();
        var frame = $('frame_'+id);
        var parts = $('parts_'+id);
        var text = $('preview_text_container_'+id);

        Event.observe($('uploader_frame'), 'load', function() {
            window.parent.location.href = url + '/' + RESTORE_NO + '/' + id;
        });

        preview(selectedContainer, photo, frame, parts, text);

        Modalbox.hide();
    }
}

function checkBlank(id) {
    var photos = Prof.photo.get_active_all(id);
    var frame = $('frame_'+id);
    var text = $('preview_text_container_'+id);

    var notblank = false;

    $A(photos).each(function(photo){
        notblank |= photo.src.match(/blank\.gif$/) != 'blank.gif';
    });
    notblank |= frame.getAttribute('rel') && frame.getAttribute('rel').match(/blank\.gif$/) != 'blank.gif';
    notblank |= text.className.match(/loaded/) == 'loaded';

    return !notblank;
}



function isInnerArea(el) {
    var innerArea = $('photoController');
    var innerArea_pos_left = parseInt(innerArea.getStyle('left').replace(/px$/, ''));
    var innerArea_pos_right = innerArea_pos_left + innerArea.getDimensions().width;
    var innerArea_pos_top = parseInt(innerArea.getStyle('top').replace(/px$/, ''));
    var innerArea_pos_bottom = innerArea_pos_top + innerArea.getDimensions().height;

    var el_pos_left = parseInt(el.getStyle('left').replace(/px$/, ''));
    var el_pos_right = el_pos_left + el.getDimensions().width;
    var el_pos_top = parseInt(el.getStyle('top').replace(/px$/, ''));
    var el_pos_bottom = el_pos_top + el.getDimensions().height;

    if(innerArea_pos_left <= el_pos_right - 1 && innerArea_pos_right >= el_pos_left + 1
    && innerArea_pos_top <= el_pos_bottom -1 && innerArea_pos_bottom >= el_pos_top + 1) {
        return true;
    }
    return false;
}

Event.observe(window, 'load', function() {
	var isIE6 = false;
	var isMSIE = /*@cc_on!@*/false;

	if(isMSIE) {
	    var arVersion = navigator.appVersion.split("MSIE");
	    var version = parseFloat(arVersion[1]);
	    if(version < 7 ) {
	        isIE6 = true;
	    }
	}


    var frames = $$('.frames');
    for(i=0;i<frames.length;i++) {
        Event.observe(frames[i], 'click', function(e) {
            var el = Event.element(e);
            if(el.rel) {
                $$('.activeFrame')[0].setAttribute('rel', el.rel);
            }else{
                $$('.activeFrame')[0].setAttribute('rel', el.src);
            }
            if(isIE6) {
                $$('.activeFrame')[0].style.filter = el.style.filter;
                return;
            }
            $$('.activeFrame')[0].setStyle({ 'background': 'url(\'' + el.src + '\') top left no-repeat' } );
        });
    }

    zoomSlider = new Control.Slider('zoom_ruler', 'zoom_ruler_bg', {
        onSlide: zoomOnSlide,
        onChange: zoomOnSlide
    });

    function zoomOnSlide(val) {
        var elements = $$('.selectedItem');
        if(elements.length) {
            var element = elements[0];
            var size = (50 * (val * 2));
            if(size < stampMinimumSize) {
                size = stampMinimumSize;
            }
            element.setStyle({'width': size + 'px', 'height': size + 'px'});
        }else if(selectPhoto) {
            var activePhoto = Prof.photo.get_active();
            activePhoto.setStyle({
                'width': (parseInt(activePhoto.getAttribute('base_width'))) * (val * 2) + 'px',
                'height': (parseInt(activePhoto.getAttribute('base_height'))) * (val * 2) + 'px'
            });
        }
        else if (selectText) {
        	$('font_size').value = parseInt(val*font_size_part)+1;
        	selectText.slider_val = val;
        	return;
        }
        $('zoom_level').value = parseInt(val * 200) + '%';
    }

    new Draggable($('photoController'), {
        'onStart': function(d, e) {
            photoDragging = true;
            var el = d.element;
            startPhotoLeft = el.getStyle('left')+22;
            startPhotoTop = el.getStyle('top')+22;

            var activePhoto = Prof.photo.get_clicked(e);//Prof.photo.get_active();
            var left = parseInt(activePhoto.getStyle('left').replace(/px$/, ''));
            var top = parseInt(activePhoto.getStyle('top').replace(/px$/, ''));

            startBackLeft = left;
            startBackTop = top;

            Prof.photo.clear_border_all();
            Prof.photo.show_border();
        },
        'onEnd': function(d, e) {
            var el = d.element;
            var border_left = parseInt($('editor_border_top').getStyle('left').replace(/px$/, ''))-22;
            var border_top = parseInt($('editor_border_top').getStyle('top').replace(/px$/, ''))-22;
            var border_width = $('editor_border_right').getDimensions().width;
            var border_height = $('editor_border_top').getDimensions().height;

            Prof.photo.clear_border_all();

            $('photoController').setStyle({'left': border_left + border_width + 'px', 'top': border_top + border_height + 'px'});
        },
        'onDrag': function(d, e) {
            var el = d.element;
            var activePhoto = Prof.photo.get_active();
            var left = startBackLeft + parseInt(el.getStyle('left').replace(/px$/, '')) - parseInt(startPhotoLeft.replace(/px$/, ''));
            var top = startBackTop + parseInt(el.getStyle('top').replace(/px$/, '')) - parseInt(startPhotoTop.replace(/px$/, ''));

            var border_left = parseInt($('editor_border_top').getStyle('left').replace(/px$/, ''));
            var border_top = parseInt($('editor_border_top').getStyle('top').replace(/px$/, ''));
            var border_right = border_left + parseInt($('editor_border_top').getDimensions().width);
            var border_bottom = border_top + parseInt($('editor_border_left').getDimensions().height) + parseInt($('editor_border_top').getDimensions().height);

            var border_width = parseInt($('editor_border_right').getDimensions().width);
            var border_height = parseInt($('editor_border_top').getDimensions().height);

            var width = parseInt(activePhoto.getDimensions().width);
            var height = parseInt(activePhoto.getDimensions().height);

            activePhoto.setStyle({'left': left + 'px', 'top': top + 'px'});
        },
        'starteffect': null,
        'endeffect': null
    });

    Event.observe($('photoController'), 'click', function(event) {
    	if (selectText) {
    		selectText.hide_border();
        	selectText = false;
        	$('palletControllerDisabler').show();
    	}
    	
        if(photoDragging) {
            photoDragging = false;
            return;
        }
        if(selectedItem) {
            selectedItem.removeClassName('selectedItem');
            selectedItem.setStyle({ 'left': parseInt(selectedItem.getStyle('left').replace(/px$/, '')) + 1 + 'px' });
            selectedItem.setStyle({ 'top': parseInt(selectedItem.getStyle('top').replace(/px$/, '')) + 1 + 'px' });
            selectedItem = null;
        }

        var activePhoto = Prof.photo.get_clicked(event);
        if (!activePhoto) return;
        var left = parseInt(activePhoto.getStyle('left').replace(/px$/, ''));
        var top = parseInt(activePhoto.getStyle('top').replace(/px$/, ''));

        if(activePhoto.src.match(/blank\.gif$/) != 'blank.gif') {
            if(activePhoto && !selectPhoto) {
                zoomSlider.setValue(parseInt(activePhoto.getStyle('width').replace(/px$/, '')) / activePhoto.getAttribute('base_width') / 2);
                $('palletControllerDisabler').hide();
                $('palletRotatorDisabler').hide();
                Prof.photo.clear_border_all();
                Prof.photo.show_border();

                $('zoom_level').style.display = 'block';
                $('font_size').style.display = 'none';
                selectPhoto = true;
            }else{
                $('palletControllerDisabler').show();
                $('palletRotatorDisabler').show();

                Prof.photo.clear_border_all();
                selectPhoto = false;
            }
        }
    });

    Prof.text.onload();
    Prof.photo.onload();

    Event.observe($('container_1'), 'click', function(el) {
        selectContainer(1);
    });
    Event.observe($('container_2'), 'click', function(el) {
        selectContainer(2);
    });

    changeContainer(1);

    $('photoSelectorDisabler').style.marginTop = '-' + $('photoSelector').getDimensions().height + 'px';
    $('photoSelectorDisabler').style.height = $('photoSelector').getDimensions().height + 'px';

    $('palletControllerDisabler').style.marginTop = '-' + $('palletController').getDimensions().height + 'px';
    $('palletControllerDisabler').style.height = $('palletController').getDimensions().height + 'px';

    $('palletRotatorDisabler').style.marginTop = '-' + $('palletRotator').getDimensions().height + 'px';
    $('palletRotatorDisabler').style.height = $('palletRotator').getDimensions().height + 'px';

    Event.observe($('buttonReset'), 'click', function() {
        $('buttonReset').blur();
        restorePreviousEditor(true);
        return true;
    });
    Event.observe($('buttonSave'), 'click', function() {
        $('buttonSave').blur();
        savePreviousEditor(true);
        return true;
    });
    Event.observe($('buttonContinue'), 'click', function() {
        $('buttonContinue').blur();
        confirmContinueNext(BASE_DIR+'order/preview');
        return true;
    });

    $('loading').hide();
});


