var rooturl = 'http://myblog.bg/';
var locale = 'bg';
var webroot = 'http://myblog.bg/';

function reloadCaptcha() {
	$('captcha_error').innerHTML = '';
	$('captcha').src = '/public/php/captcha.php?' + Math.floor(Math.random()*1000);
}

function extraInfo() {
	
	$('optional_fields').toggle();
	
    if ($('optional_fields').style.display != 'none') {
        createCookie('optional_fields_state', 1, 1);
        $('extra_info_link').removeClassName('extra_info_plus');
        $('extra_info_link').addClassName('extra_info_minus');
    } else {
        createCookie('optional_fields_state', 0, 1);
        $('extra_info_link').removeClassName('extra_info_minus');
        $('extra_info_link').addClassName('extra_info_plus');
    }
}

function avatarPreview() {
	
	if ($('member_avatar_url').value != '') {
		$('avatar_holder').src = $('member_avatar_url').value;
	}
}

function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


/**
 * Toggle lost_password & reactivation form.
 */
function toggle_lost_password() {
	if ($('lost_reactivate')) {
		$('lost_reactivate').action = rooturl + 'lost_password';
		$('activation_link_label').show();
		$('reactivate_form_label').hide();
		$('lost_password_link_label').hide();
		$('lost_form_label').show();
		
		$('member_email_error_secondary').innerHTML = '';
		$('member_email_secondary').className = 'long';
	}
	
	return false;
}
function toggle_reactionvation() {
	if ($('lost_reactivate')) {
		$('lost_reactivate').action = rooturl + 'reactivation';
		$('lost_form_label').hide();
		$('activation_link_label').hide();
		$('reactivate_form_label').show();
		$('lost_password_link_label').show();
		
		$('member_email_error_secondary').innerHTML = '';
		$('member_email_secondary').className = 'long';
	}
	
	return false;
}


var networkTimeout = 0;
function show_network(){
	clearTimeout(networkTimeout);
	$('networks').show();
}
function hide_network(){
	networkTimeout = setTimeout('close_butt()', 3000);
}
function show_more(){
	$('net_buttons').setStyle({'width': '360px'});
	$('more_networks').setStyle({'width': '350px'});
	$('more_links').show();
	$('more_net').hide();
	$('close_net').show();
}
function show_more(){
	$('net_buttons').setStyle({'width': '360px'});
	$('more_networks').setStyle({'width': '350px'});
	$('more_links').show();
	$('more_net').hide();
	$('close_net').show();
}
function close_butt(){
	$('networks').hide();
	$('net_buttons').setStyle({'width': '240px'});
	$('more_networks').setStyle({'width': '230px'});
	$('more_links').hide();
	$('more_net').show();
	$('close_net').hide();
}

function toggleEditor(id) {
	var elm = document.getElementById(id);

	if (tinyMCE.getInstanceById(id) == null){
		tinyMCE.execCommand('mceAddControl', false, id);
	}
	else{
		tinyMCE.execCommand('mceRemoveControl', false, id);
	}
}

function vote(id, voting){
	new Ajax.Request( rooturl + locale + "/ajax/vote", {
		method: "get",
		parameters: {"id" : id, "voting" : voting},
		onSuccess: function(transport) {
			$("votings").update(transport.responseText);
			$("vote").hide();
		}
	});
}

function save_post(isDraft){
	saveEditors();
	$$('div.errormsg').each(function(e){e.update('').hide();})
	$('saving_status').removeClassName('saving-error');
	$('saving_status').removeClassName('saving-success');
	$('saving_status').update(msg_save_loading).show();
	$('preview_status').update('');

	if(isDraft == true){
		$('f-isdraft').value = 1;
	}
	else{
		$('f-isdraft').value = 0;
	}

	if(form_initial_state == $('form-settings').serialize() && isDraft == false){
		$('saving_status').update(msg_save_no_changes);
	}
	else{

		$('form-settings').request({
			method: 'post',
			parameters: { save: 1, rand: Math.floor(Math.random() * 100000000) },
			onSuccess: function(transport){
				var r = transport.responseText.evalJSON();
				if(r.postId !=0){$('f-postId').value=r.postId;};
				if(r.error_count == 0 && $('f-postId').value != 0)
				{
					if($('f-isdraft').value == 1)
					{
						$('preview_status').update(msg_draft_post);
					}
					else
					{
						var post_url = blog_domain + 'post/' + $('f-postId').value;
						var searchStr = "blog_domain";
						var re = new RegExp(searchStr , "g");
						var msg = msg_preview_post.replace(re, post_url);
						$('preview_status').update(msg);
					}
					$('preview_status').show();
				}
				setErrorFields(transport.responseText);
			},
			onFailure: function(transport){ setErrorFields('{ "error_count": 0, "error_fields": {}, "save_success": 0 }'); }
		});
	}
}

function save_settings(){
	saveEditors();
	$$('div.errormsg').each(function(e){e.update('').hide();})
	$('saving_status').removeClassName('saving-error');
	$('saving_status').removeClassName('saving-success');
	$('saving_status').update(msg_save_loading).show();
	if(form_initial_state == $('form-settings').serialize()){
		$('saving_status').update(msg_save_no_changes);
	}
	else{
		$('form-settings').request({
			method: 'post',
			parameters: { save: 1, rand: Math.floor(Math.random() * 100000000) },
			onSuccess: function(transport){	setErrorFields(transport.responseText); },
			onFailure: function(transport){	setErrorFields('{ "error_count": 0, "error_fields": {}, "save_success": 0 }'); }
		});
	}
	return false;
}

function setErrorFields(response){
	// alert(response);
	var r = response.evalJSON();
	if(typeof(r.redirect) != "undefined"){
		form_initial_state = $('form-settings').serialize();
		window.location.href = r.redirect;
		return;
	}
	if(r.error_count > 0){
		$('saving_status').addClassName('saving-error').update(msg_save_form_error);
		$('saving_status').show();
		for (var field in r.error_fields){
			$('error_'+field).update(eval('msg_error_'+field));
			$('error_'+field).show();
		}
	}
	else if(r.save_success == 0){
		$('saving_status').addClassName('saving-error').update(msg_save_error);
		$('saving_status').show();
	}
	else{
		$('saving_status').addClassName('saving-success').update(msg_save_success);
		$('saving_status').show();
		form_initial_state = $('form-settings').serialize();
	}
	// call a specific function for the form page [usually not neccesary]
	if(typeof(formSuccess) == "function")
	{
		formSuccess(r);
	}
}

function compareForm(){
	saveEditors();
	if( $('form-settings') && form_initial_state != $('form-settings').serialize()){
		return msg_discard_changes;
	}
}

function saveEditors(){
	if(typeof(editor_elements) == "undefined")
		return;
	for( i = 0; i < editor_elements.length ; i++){
		var editor = tinyMCE.getInstanceById(editor_elements[i]);
		if(editor != null){
			$(editor_elements[i]).value = editor.getContent();
		}
	}
}

function d(obj){
	for(var i in obj){
		alert('obj['+i+']= '+obj[i]);
	}
}

var TemplateBlocks = {
	blocks : [],
	windows : {},
	setBlocks : function(blocks_array){
		this.blocks = blocks_array;
		blocks_array.each(function(b) {
			TemplateBlocks.setSortable(b, blocks_array, 'draggable');
		});
	},
	setSortable : function(block_id, allowed_blocks, draggable){
		Sortable.create(block_id,
		 {	dropOnEmpty:true,
			containment: allowed_blocks,
			tag:'li',
			constraint:false,
			overlap:'vertical',
			only:draggable,
			onUpdate:function(){ TemplateBlocks.serialize(); }
		 });
	},
	checkSortables : function(){
		// ToDo: check maxwidgets limit reached
	},
	serialize : function(){
		this.blocks.each(function(b) {
			var s = Sortable.sequence(b);
			$('f-data_'+b).value = s;
		});
	},
	prepareForSubmit : function(){
		this.blocks.each(function(b) {
			TemplateBlocks.setSortable(b, this.blocks, false);
		});
		this.serialize();
		this.blocks.each(function(b) {
			TemplateBlocks.setSortable(b, this.blocks, 'draggable');
		});
	},
	clearChanges : function(){
		var initial_state = $('initial-state').innerHTML;
		var re = new RegExp('initial-', "g");
		var initital_content = initial_state.replace(re, '');
		$('current-state').update(initital_content);
		this.prepareForSubmit();
		form_initial_state = $('form-settings').serialize();
	},
	open : function(action, blogId, block_id, widget_id){
		win_settings = 'status,resizable,dependent,scrollbars,width=570,height=500';
		if(action == 'edit'){
			win_id = 'editWidget'+widget_id;
			// win_url = 'configure-widget.go?js=1&action=update&blogId='+blogId+'&block='+block_id+'&widget='+widget_id+'&type='+widget_type;
			win_url = rooturl + locale + '/widgets/edit/'+blogId+'?pop=1&widget_id='+widget_id;
		}
		else{
			win_id = 'newWidgetIn'+block_id;
			win_url = rooturl + locale + '/widgets/select/'+blogId+'?pop=1&block='+block_id;
		}
		this.windows[win_id] =  window.open(win_url,win_id,win_settings);
		return false;
	},
	updateWidgets : function(data){
		var w_id = data["widgetId"];
		var w_block = data["block"];
		var w_title = data["title"];
		var w_delete = parseInt(data["delete"]);

		var w_window = this.windows[data["window"]];
		w_window.close();
		delete(this.windows[data["window"]]);

		if(w_delete == 1){
			$('widget_'+w_id).parentNode.removeChild($('widget_'+w_id));
			$('initial-widget_'+w_id).parentNode.removeChild($('initial-widget_'+w_id));

			// var f = $('f-data_'+w_block).value;
			// var re = new RegExp(w_block+"\[\]="+w_id, "gi");
			// $('f-data_'+w_block).value = f.replace(re, '');
			return;
		}

		if($('widget_'+w_id)){
			$('widget-title_'+w_id).update(w_title);
			$('initial-widget-title_'+w_id).update(w_title);
			this.serialize(true);
		}
		else{
			var syntax = /(^|.|\r|\n)(\#\[\s*(\w+)\s*\])/; //matches symbols like '#[field]'
			var t = new Template($('widget-template').innerHTML, syntax);

			var widget = t.evaluate( {'initial': '', 'widgetId': w_id, 'title': w_title, 'block': w_block} );
			var sblock = new Element('li', { 'id': 'widget_'+w_id, 'class': 'draggable' });
			sblock.innerHTML = widget;

			var widget_initial = t.evaluate( {'initial': 'initial-', 'widgetId': w_id, 'title': w_title, 'block': w_block } );
			var sblock_initial = new Element('li', { 'id': 'initial-widget_'+w_id, 'class': 'draggable' });
			sblock_initial.innerHTML = widget_initial;

			$('block_'+w_block).insertBefore(sblock,$('block_'+w_block).firstChild);
			$('initial-block_'+w_block).insertBefore(sblock_initial,$('initial-block_'+w_block).firstChild);
			this.serialize(true);
			Sortable.destroy('block_'+w_block);
			this.setSortable('block_'+w_block, this.blocks, 'draggable');
		}
	}
};

var skinStyler = {
	_currentStyle : {},
	_currentValue : {},
	setCurrentStyle : function(name){
		if(typeof(skins[name]) != "undefined")
			this._currentStyle = skins[name];
		else
			return true;

		if(this._currentStyle.type == "font"){
			var sArray = this._currentStyle.value.strip().split('%');
			var styles = sArray[0].split(' ');
			var re = new RegExp("arial|courier|times|trebuchet|georgia|verdana", "gi");
			var face = sArray[1].match(re);
			face = face[0].toLowerCase();
			this._currentValue = {'italic':styles[0], 'bold':styles[1], 'size':parseInt(styles[2]), 'face':sArray[1].strip()};
			$('font-italic').checked = (this._currentValue.italic == 'italic');
			$('font-bold').checked = (this._currentValue.bold == 'bold');
			$('font-face-'+face).checked = true;
		}
		else{
			this._currentValue = this._currentStyle.value;
		}
		this.setForms();
	},
	setColor : function(hexColor){
		if(this._currentStyle.type == "color"){
			this._currentValue = hexColor;
			this.updatePreview();
		}
	},
	setFontFace : function(id){
		if(this._currentStyle.type == "font"){
			this._currentValue.face = $(id).value;
			this.updatePreview();
		}
	},
	checkBoldFont : function(){
		if(this._currentStyle.type == "font"){
			this._currentValue.bold = ($('font-bold').checked == true) ? 'bold' : 'normal';
			this.updatePreview();
		}
	},
	checkItalicFont : function(){
		if(this._currentStyle.type == "font"){
			this._currentValue.italic = ($('font-italic').checked == true) ? 'italic' : 'normal';
			this.updatePreview();
		}
	},
	resizeFontBigger : function(){
		if(this._currentStyle.type == "font"){
			this._currentValue.size = this._currentValue.size + 10;
			this.updatePreview();
		}
	},
	resizeFontSmaller : function(){
		if(this._currentStyle.type == "font"){
			this._currentValue.size = this._currentValue.size - 10;
			if(this._currentValue.size <= 0){
				this._currentValue.size = 10;
			}
			this.updatePreview();
		}
	},
	setForms : function(){
		$('skin-color-settings', 'skin-font-settings').invoke('hide');
		$('skin-' + this._currentStyle.type + '-settings').show();
		$(this._currentStyle.type + '-title').update(this._currentStyle.description);
		this.updatePreview();
	},
	updatePreview : function(){
		if(this._currentStyle.type == "font"){
			var cv = this._currentValue;
			var font = cv.italic + ' ' + cv.bold + ' ' + cv.size + '% ' + cv.face;
			$('f-' + this._currentStyle.name).value = font;
			$('p-' + this._currentStyle.name).setStyle({'font':font});
			$('skin-font-preview').setStyle({'font':font});
		}
		else{
			$('f-' + this._currentStyle.name).value = this._currentValue;
			$('p-' + this._currentStyle.name).setStyle({'background':this._currentValue});
			$('skin-color-preview').setStyle({'background':this._currentValue});
		}
	},
	returnDefaultSkin : function(){
		for(var skin in skins){
			skins[skin]['value'] = skins[skin]['default'];
			$('f-' + skin).value = skins[skin]['default'];
			if(skins[skin]['type'] == "font"){
				$('p-' + skin).setStyle({'font':skins[skin]['default']});
			}
			else{
				$('p-' + skin).setStyle({'background':skins[skin]['default']});
			}
		}
		this.setCurrentStyle(this._currentStyle.name);
	}
};

var Dependance = {
	checkbox: function(element_id, dependants){
		dependants.each(function(d){
			$(d).disabled = !$(element_id).checked;
		});
		Event.observe($(element_id), "change", function(){
			dependants.each(function(d){
				$(d).disabled = !$(element_id).checked;
			});
		});
		Event.observe($(element_id), "click", function(){
			dependants.each(function(d){
				//$(d).checked = $(element_id).checked;
				$(d).disabled = !$(element_id).checked;
			});
		});
	}
}

var form_initial_state;
Event.observe(window, 'load', function() {
	if($('form-settings')){
		form_initial_state = $('form-settings').serialize();
	}
});
var form_editor_areas = [];
window.onbeforeunload = function(){ return compareForm(); }

var MSlider = {
	start: function(sliding_elem, direction, speed){
		if(typeof(sliding_elem) == "undefined") sliding_elem = "templates-slider";
		if(typeof(direction) == "undefined" || (direction != "top" && direction != "bottom")) direction = "top";
		if(typeof(speed) != "undefined") MSlider.speed = parseInt(speed);
		MSlider.current_elem = $(sliding_elem);
		MSlider.movement = (direction == "top") ? 1 : -1;
		MSlider.movement = MSlider.movement * MSlider.speed;
		MSlider.current_height = MSlider.current_elem.getHeight();
		MSlider.parent_height = $(MSlider.current_elem.parentNode).getHeight();
		if(MSlider.current_height > MSlider.parent_height){
			MSlider.currentInterval = setInterval('MSlider.slide()', 10);
		}
	},
	slide: function(){
		var top = parseInt(MSlider.current_elem.getStyle('top'));
		top = top + MSlider.movement;
		if(top > 0 && MSlider.movement > 0){
			MSlider.current_elem.setStyle({"top" : "0px"});
			MSlider.stop();
			return;
		}
		if(top < (MSlider.parent_height - MSlider.current_height) && MSlider.movement < 0){
			MSlider.current_elem.setStyle({"top" : (MSlider.parent_height - MSlider.current_height)+"px"});
			MSlider.stop();
			return;
		}
		MSlider.current_elem.setStyle({"top": top+"px"});
	},
	stop: function(){
		clearInterval(MSlider.currentInterval);
		MSlider.movement = 0;
		MSlider.speed = 10;
		MSlider.current_elem = false;
	},
	movement: 0,
	speed: 10,
	currentInterval: false,
	current_elem: false,
	current_height: 0,
	parent_height: 0
};


function changeTab (show_type, hide_type, button){
	$(hide_type).hide();
	$(show_type).show();
	if (button=='tab_violet') {
		tab='tab_top_blog';
	}
	else tab = 'tab_violet';
	$(tab).removeClassName('active');
	$(tab).addClassName('inactive');
	$(button).removeClassName('inactive');
	$(button).addClassName('active');
}
