// global Prototype
var Mockcenter = function(){
return {
 gui : function(){},
 ajax : function(){},
 helpers : function(){}
};
}();

$.fn.center = function(){
        var self = this;
	var dim = [$(window).height(),self.height(),$(window).width(),self.width()]
	for (var i = 0; i<2; i++){
	  var kjoer = dim[0]>dim[1]?Math.round((dim.shift()-dim.shift())/2):(function(){dim.shift();dim.shift();return 0;})();
	  dim.push(kjoer);
	}
	self.css("top", dim.shift() ).css("left", dim.shift() );
	return self;
	};

Mockcenter.gui.fadebar = function(domobj){
  domobj.each(function(){
    $(this).hover(
      function(){
        $(this).fadeTo(200,1);
      }, function(){
        $(this).fadeTo(200, 0.3);
    }).fadeTo(50, 0.3);
  });
};


// still needed? //
function changeSrc(sr){ 
$("#bgframe").attr("src", sr); 
$("#shader").add("#bgselector").hide();
}
// ?!? //


// class Olay //

var Olay = function(fp,prefix){
var self = this;
this.open = function(){
$("#preview_feed").hide();
if (fp==true){ 
  $("#bgselector").fadeIn("slow");
  } else {
  $("#bgselector").show().animate({top: "0px"}, 1000, function(){$("#preview_feed").show()});
  var sn = get_values();
  var b = make_url(sn);
  $("#shader").show();
  $("#preview_feed").width($("#nfeed").width())
                    .height($("#nfeed").height());
  $("#snapshot_feed_width").attr("value", $("#nfeed").width());
  $("#snapshot_feed_height").attr("value", $("#nfeed").height());
  $("#trackback").html("<a href=\""+b+"\">"+b+"</a>");
  $("#preview_url").val(b);
  $("#snapshot_bgcolor").attr("value", sn[7]);
  $("#snapshot_width").attr("value", sn[0]);
  $("#snapshot_height").attr("value", sn[1]);
  $("#snapshot_pos_x").attr("value", sn[5]);
  $("#snapshot_pos_y").attr("value", sn[6]);
}
}

this.close = function(){

$("#preview_feed").hide();
  $("#bgselector").animate({top: 0 - $("#bgselector").height() },"slow", function(){$("#shader").hide()});

}

this.init = function() {
var wh = $(window).height();
var ww = $(window).width();
if (fp==false){
 $("<div></div>").attr("id", "shader").fadeTo(100, 0.5)
 .css("background", "#70CDE3 url("+prefix+"images/selec_bg.gif) repeat-x top left")
 .width("100%").height($(window).height()).css("position", "absolute").css("top", "0px").css("left", "0px").hide().insertBefore("#bgselector").hide()
 .css("z-index", "99998").add("#overlay_close")
 .click(function(){
   self.close();
 });
}
var d = 1024;
$("#bgselector").width(d).css("position", "absolute").css("top", 0 - $("#bgselector").height()).css("left", (ww-d)/2).css("background", "white")
.css("z-index", "99999");
if (fp == true) $("#bgselector").css("top", (wh-700)/2)
}


}


// /olay //

// class Ajx //

var Ajx = function(prefix){
// old #user_form submission data: { email: $("#user_form_email").val(), preview_url: $("#preview_url").val() }


	var self = this;

	this.init = function(){

		this.register_links();
		this.register_forms();
		$("#mock_list_link").unbind("click").click(function(){
			$.get( prefix+'snapshots/xlist', { start: 0 }, function(data){
			$("#mock_list").html(data);
		});
		return false;});
	};

	this.register_forms = function(){
		$("form.asynch").unbind("submit").submit(function(){
			try {
			  $(this).attr("action").match(/DOMtarget=([^&]+)/);
			  var target = "#" + RegExp.$1;
			  $.post( $(this).attr("action"), $(this).serialize(), function(data){ $(target).html(data); self.register_links(); self.register_forms(); } )
                          return false;
			} catch(e) { 
			  alert(e); 
			  return false; 
			};
		});
	};

//	this.user_form_old = function(){
//
//		$("#user_form").unbind("submit").submit(function(){
//		        sn = get_values()
//			$.post( prefix+'account/xlogin', 
//			{ email: $("#user_form_email").val(), 
//                        // preview_url: $("#preview_url").val(),
//			  url: (sn[2]||$("#bgframe").attr("src")), xid: s_xid, w: sn[0], h:sn[1], x:sn[5], y: sn[6], bg:sn[7] }
//			, function(data){
//			$("#bgselector").empty().prepend(data);
//		});
//		return false;
//		});
//	}

	this.register_links = function(){
		$("a").focus(function(){this.blur()}).filter("[href='']").click(function(){ return false; });
		$("a.asynch").unbind("click").click(function(){
			var params = [];
			params[0] = $(this).attr('href').replace(/DOMtarget=([^&]+)&?/, '');
			params[1] = RegExp.$1;
			return self.update(params[0],'#'+params[1]);
		});
	};

	this.save_as_new = function(){
		$.post(prefix+'snapshots/save_as_new', $("#editor").serialize() , function(data){$("#flash_notice").html('');
                     // $("#mock_list").html(data);
                     $("#bgselector").empty().prepend(data); app_events.reinit();
		$("#sn_url a").html($(data).children("ul li").children("a").html()).attr("href", $(data).children("ul li").children("a").html());
		})}
        
        this.commit = function(trgt){
            $.post(trgt, $("#editor").serialize(), function(data){
                     $("#bgselector").empty().prepend(data);
                     app_events.reinit();
             })
        };

	this.template_showcase = function(id){
	$.get(prefix+'template/xshow/'+id, {} , function(data){
		$("#template_showcase").hide().replaceWith(data).show()
		})
	}
	
	this.update = function(trgt,dom_element,callback) {
	
		// set decent values
		dom_element = !dom_element ? "#flash_notice" : dom_element;
		callback = !callback ? function(){ return false; } : callback;
		$("#flash_notice").html('please wait a second...');
		$.post(trgt, $("#editor").serialize() , function(data){ $(dom_element).html(data); self.register_links(); self.register_forms(); callback(); } );
		return false;
		
	}

	self.init();

};

// /Ajx //

// class Events //

var Events = function(overlay){

var self = this;


this.init = (function(){
$("a#a1").click(function(){
  var dom = $("#instruction")
  if (dom.css("display")=="none"){
    dom.show();
    }
  else {
	dom.hide()
    }
  $("#nfeed").toggleClass("borderblue");
  if ($("#a1").html() == "fix feed"){
  $("#a1").empty().html("move feed").add("#snapshot_fixed").attr("value", "true");}
  else
  {
  $("#a1").empty().html("fix feed").add("#snapshot_fixed").attr("value", "false");}
  });



$("#a2").click(function(){
  overlay.open()
});


$("#a3").add("#cp_close a").click(function(){
 obj = $("#colorpicker")
 if (obj.is(".hidden")) {
  obj.fadeIn("slow").removeClass("hidden");
 }
 else {
  obj.hide().addClass("hidden");
 }
});


$("#nfeed").mouseout(function(){
var d = parseInt($(this).css("left"));
var e = parseInt($(this).css("top"));
$("#snapshot_pos_x").attr("value", d);
$("#snapshot_pos_y").attr("value", e);
});

$("#form_preview_button").click(sn_preview);
// sliders
$("#slideknob").slider("#nfeed_frame", "width", 100, 600, "#nfeed");
$("#slideknob2").slider("#nfeed_frame", "height", 100, 570, "#nfeed");
// until here

$("#snapshot_xmplfeed_id").change(function(val){update_preview(val)});

$("#cp_hex_box").click(function(){
	if ($(this).attr("checked")) {
		$("#nfeed").css("background-color", "#"+$("#cp_hex").val());cp.override(true);
		if ($("#transparency").attr("checked")) {
			$("#transparency").removeAttr("checked")
		}
	}
	else { 
		cp.override(false); cp.set_bg()
	}
});

$('#draw_feed').click(function(){

$('<div/>').attr('id','draw_board').width(1008).height(1500).css("position", "absolute")
 .css("top", "0px")
 .css("left", "0px") // .css('display','none')
 .css("background", "#888")
 .insertAfter("#nfeed").fadeTo(200, 0.33).html('<h1>click and draw mouse</h1>');

     $('#draw_board').mousedown(function(e){
       $('#nfeed').hide();
       var pageX = e.pageX ? e.pageX : e.clientX;
       var pageY = e.pageY ? e.pageY : e.clientY;
       $('<div/>').attr('id','draw_helper').css({ 'left': pageX +'px', 'top': pageY + 'px', 'border': '1px dotted black', 'position':'absolute' }).appendTo('body');
       $('#draw_board').add('#draw_helper').mousemove(function(e){
         if ( $('#draw_helper').length > 1 ) {
           $('#draw_helper').slice(1).remove()
         } 
         var deltaX = pageX - e.pageX;
         var deltaY = pageY - e.pageY;
         if ( deltaX < 0 ) {
           $('#draw_helper').css('left', pageX)
           $('#draw_helper').width(-1 * deltaX);
         } else {
           $('#draw_helper').css('left', e.pageX).width(deltaX);
         };
         if ( deltaY < 0 ) {
           $('#draw_helper').css('top', pageY)
           $('#draw_helper').height(-1 * deltaY);
         } else {
           $('#draw_helper').css('top', e.pageY).height(deltaY);
         }
       });
     });

     var update = function(){
       var draw_board = document.getElementById('framecont')
       var xpos = parseInt( $('#draw_helper').css('left') ,10 ) -  parseInt( draw_board.offsetLeft, 10 );
       var xdim = parseInt( $('#draw_helper').width(), 10 );
       var ypos = parseInt( $('#draw_helper').css('top') ,10 ) - parseInt( draw_board.offsetTop, 10 ) + draw_board.scrollTop;
       var ydim = parseInt( $('#draw_helper').height(), 10 );
       if ( xdim > 10 || ydim > 10 ) {
         $('#nfeed').css('left', xpos + 'px').width(xdim).css('top', ypos + 'px').height(ydim);
         $('#nfeed_frame').width(xdim).height(ydim);
       };
         $('#draw_board').unbind('mousemove').remove();
         $('#draw_board').remove();
         $('#draw_helper').remove();
         $('#nfeed').show();
     };

     $('body').mouseup(function(){
       update();
     });

return false;
});

$("#transparency").click(function(){
	if ($(this).attr("checked")) {
		$("#nfeed").css("background", "transparent");
		cp.override(true);
		if ($("#cp_hex_box").attr("checked")) {
			$("#cp_hex_box").removeAttr("checked")
		}
	}
	else {
		cp.override(false);
		cp.set_bg();
	};
});


})();

};

// /class Events //

// form handling //

function form_submit(trgt, id){
if (trgt == 'edit'){

app_ajax.update('/snapshots/update/'+id,'#flash_notice', function(){ });

//$("#bgframe").attr("src", $("#snapshot_url").val());
//$("#flash_notice").html('please wait a second...')
//$.post('/snapshots/update/'+id, $("#editor").serialize() , function(data){$("#flash_notice").html(data)})
//document.editor.action = '/snapshots/update/' + id;
//document.editor.submit();
}
if (trgt == 'save_as_new'){
$("#bgframe").attr("src", $("#snapshot_url").val());
document.editor.action = '/snapshots/save_as_new/';
$("#flash_notice").html('please wait a second...')
app_ajax.save_as_new()
//document.editor.submit();
}
if (trgt == 'login'){
document.form.action = '/account/login/';
document.form.submit();
}
}

// /form handling //


// helpers //


function get_values(){
var sn = [ $("#nfeed").attr("value", $(this).width()).width(),
$("#nfeed").attr("value", $(this).height()).height(),
$("#snapshot_url").attr("value"),
$("#snapshot_bgcolor").attr("value"),
$(".xmplfeed_options").eq(($("#snapshot_xmplfeed_id").attr("value") - 1)).attr("name"),
parseInt( $("#nfeed").css("left"), 10 ),
parseInt( $("#nfeed").css("top"), 10 ) ];
sn[7] = $("#nfeed").css("background-color")=='transparent'?'transparent':color_value()
return sn;
};

function color_value() {
var re = /(\d+), (\d+), (\d+)/;
var mtch = re.exec($("#nfeed").css("background-color"))
return $("#nfeed").css("background-color").match(/#/)?$("#nfeed").css("background-color").substring(1,7):parseInt(mtch[1]).toString(16)+parseInt(mtch[2]).toString(16)+parseInt(mtch[3]).toString(16)
}

function sn_preview(){
var z = "nil";
var sn = get_values();
$("#preview_feed").add("#nfeed_frame").add("#nfeed").attr("width", sn[0]).attr("height", sn[1]);
$("#bgframe").attr("src", sn[2]);
$("#form_preview_frame").add("#nfeed_frame").css("background", sn[3]);
$("#preview_feed").add("#nfeed_frame").attr("src", sn[4]);
}

function addShade(){
$("<div class='shad'></div>").width("1008px").height("1500px").css("position", "absolute")
 .css("top", "0px")
 .css("left", "0px")
 .css("background", "transparent")
 .html("<img src='' alt='nil' width='1008' height='1500' border='0'/>")
 .insertBefore("#nfeed");
}

function hideShade(){
$("div.shad").remove();
}

function parse_url(){
var url_part = $("#url_part").val();
var par = parent.location.href.match(/^http:\/\/[^#^\s]+/);
if (url_part.match(/\w+\.\w+/) && !url_part.match(/google/) && !url_part.match(/^http:\/\//)){
parent.location = par+'&url=http://'+url_part; return true;
} else
{ $("#message").html("Naaah. Try again.").show().fadeOut(5000);  return false;
};
};

function make_url(sn){
return document.URL.match(/^http.+?\/snapshots\//)+'new?url='+s_url+'&xid='+s_xid+'&w='+sn[0]+'&h='+sn[1]+'&x='+sn[5]+'&y='+sn[6]+'&bg='+sn[7];
};

function update_preview(val) {
$("#preview_feed").add("#nfeed iframe").attr("src", $("#snapshot_xmplfeed_id option").eq($("#snapshot_xmplfeed_id").val()-1).attr("name"))
}

function fixPng() {
	$("<div/>").attr("id", "debug").appendTo("#bgselector").css({"background":"#ddddff", "z-index":"300", "color":"#00447C", "position": "absolute", "top": "100", "left": "10%", "filter": "alpha(opacity=80)", "width": "80%", "display":"none"})
	$("img").each(function(){
		$("#debug").html($("#debug").html()+this.src+'<br/>')
		if (this.src.match(/png$/)){
			$("#debug").html($("#debug").html()+this.src+'<br/>')
			this.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',src='"+this.src+"')";
		}
		})
	$("div").each(function(){
		if ($(this).css("background-image") != 'none' && $(this).attr("id") != 'navbar' && $(this).attr("class") != 'button_cyan_left' && $(this).attr("class") != 'slider_right' && $(this).attr("class") != 'slider_left' && $(this).attr("class") != 'slidespacer'  ){
			var a=$(this).css("background-image").match(/http[^"^']+/)
			$(this).css("background-image", "none")
			this.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',src='"+a+"')";
			$("#debug").html($("#debug").html()+$(this).attr("class")+':'+$(this).attr("id")+':'+$(this).css("background-image").match(/http[^"^']+/)+':'+$(this).css("filter")+'<br/>')
		}
		})
	}

// /helpers //

// colorpicker //

var colorpicker = function(obj){
var self = this;
var r,g,b,h,s,l,o;

this.set_bg = function(){
if (o == false) {
var first = Math.round((s*255+(1-s)*r)*l).toString(16).length==1?"0"+Math.round((s*255+(1-s)*r)*l).toString(16):Math.round((s*255+(1-s)*r)*l).toString(16)
var second = Math.round((s*255+(1-s)*g)*l).toString(16).length==1?"0"+Math.round((s*255+(1-s)*g)*l).toString(16):Math.round((s*255+(1-s)*g)*l).toString(16)
var third = Math.round((s*255+(1-s)*b)*l).toString(16).length==1?"0"+Math.round((s*255+(1-s)*b)*l).toString(16):Math.round((s*255+(1-s)*b)*l).toString(16)
var cc = '#'+first+second+third;
$(obj).css("background-color",cc);
$("#cp_hex").val(cc.slice(1,7));
return s+'::'+l+'::'+h+'::'+Math.round(r)+'::'+Math.round(g)+'::'+Math.round(b)+'::'+cc; }
else { 
return false; };
}

this.override = function(val){
o = val;
return true;
}

this.test = function(val){
return true;
}

this.set_hue = function(val){
val = val/255 * 6
h = val
if (val < 1) {
r = 255
g = val * 255
b = 0
}
if (val>=1 && val < 2){
val = val - 1;
r = (1-val)*255
g = 255
b = 0
}
if (val>=2 && val < 3){
val = val -2
r = 0
g = 255
b = val * 255
}
if (val>=3 && val < 4){
val = val - 3;
r = 0
g = (1-val)*255
b = 255
}
if (val>=4 && val < 5){
val = val -4
r = val * 255
g = 0
b = 255
}
if (val>=5 && val < 6){
val = val - 5;
r = 255
g = 0
b = (1-val)*255
}

return self.set_bg();
}

this.set_light = function(val){
l = val/255;
return self.set_bg();
}

this.set_sat = function(val){
s = 1-(val/255)
if (s <=0.066) s = 0.066;
return self.set_bg()
}

this.init = (function(){
r=255;g=0;b=0;h=255;s=1;l=1;o=false;
self.set_bg();
})();
}
