// Set, Get and Erase Cookies

setCookie = function(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+";";
}

getCookie = function(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;
}

eraseCookie = function(name) {
	setCookie(name,"",-1);
}


editMe_mouseover = function() { //On Mouse Over
        //Collect current border information and create border.
        var divSize = new Array();
        divSize[0] = $(this).width();
        divSize[1] = $(this).height();
        divSize[2] = $(this).position();
        divSize[3] = $(this).css('marginTop');
        divSize[4] = $(this).css('marginRight');
        divSize[5] = $(this).css('marginBottom');
        divSize[6] = $(this).css('marginLeft');
        divSize[7] = $(this).css('paddingTop');
        divSize[8] = $(this).css('paddingRight');
        divSize[9] = $(this).css('paddingBottom');
        divSize[10] = $(this).css('paddingLeft');
        divSize[11] = $(this).css('border-top-width');
        divSize[12] = $(this).css('border-right-width');
        divSize[13] = $(this).css('border-bottom-width');
        divSize[14] = $(this).css('border-left-width');
        $(this).parent().trigger('mouseout');
        $(this).prepend('<div class="whip_hover_box"><img class="whip_edit_button" src="/templates/version1/css/images/edit_button.png"/><div class="whip_highlight"></div></div>');
        $("div.whip_hover_box").css('width', parseInt(divSize[0])+20);
        $("div.whip_hover_box").css('height', parseInt(divSize[1])+20);
        $("div.whip_hover_box").css('paddingTop',parseInt(divSize[3])+parseInt(divSize[7])+parseInt(divSize[11])-10);
        $("div.whip_hover_box").css('paddingRight',parseInt(divSize[4])+parseInt(divSize[8])+parseInt(divSize[12]));
        $("div.whip_hover_box").css('paddingBottom',parseInt(divSize[5])+parseInt(divSize[9])+parseInt(divSize[13]));
        $("div.whip_hover_box").css('paddingLeft',parseInt(divSize[6])+parseInt(divSize[10])+parseInt(divSize[14])-10);
        $("div.whip_hover_box").css('top', parseInt(divSize[2].top)-10);
        $("div.whip_hover_box").css('left',parseInt(divSize[2].left)-10);

    }

editMe_mouseout = function() { //On Mouse Out
        //Return border to previous state.
        $(this).parent().trigger('mouseover');
        $(".whip_hover_box").remove();
        $("div.whip_highlight").css('cursor', 'default');
    }

editMe_click = function() {
		if(typeof whip_task == 'undefined') {whip_task = 'edit_content';}
		whip_editingID = $(this).attr("id");
		whip_editingClass = $(this).attr("class");
		load_WhipScreen();
    }

load_WhipScreen = function() {

		if(typeof whip_editor_box == 'undefined') {
			$("body").prepend('<div id="whip_editor_box"><img class="whip_shade" src="/templates/version1/css/images/shade.png"/><div class="whip_editor_wrap"><div id="whip_editor"></div><div class="clear"></div></div></div>');
		}
        $("div#whip_editor").stop(true, true).load('ajax','task='+whip_task+'&path='+escape(window.location.pathname)+escape(window.location.hash)+'&id='+whip_editingID+'&classes='+whip_editingClass,function(){
        editor_saveAction();
		});
		$(".whip_hover_box").remove();
		
        window.scroll(0,0);
        
}

set_sortables = function() {

	$( ".sortable" ).sortable({
		helper: 'clone',
		update: function(event, ui) {
			var sortIDs = $(this).sortable( "serialize", {key : 'key[]'});
			$.post('/whip/sort_list', sortIDs, function(response) {
			set_preview_mode(escape(window.location.pathname)+escape(window.location.hash));
			});
		}
	});

}

edit_return = function() {

		load_WhipScreen();
		whip_task='edit_content';
}

set_preview_mode = function(response) {
	
			setCookie('whip_view','Preview',0);
			$(".preview_mode").css('display','inline');
			var saveUrl = '/whip/save_changes'+response;
			var cancelUrl = '/whip/cancel_changes'+response;
			setCookie('whip_save',saveUrl,0);
			$("#preview_save a").attr('href',saveUrl);
			$("#preview_cancel a").attr('href',cancelUrl);
			
}

editor_saveAction = function() {
		$(".sub_editable").click(subEditMe_click);
		$(".delete_me").click(deleteMe_click);
		$("#EditSubmit").click(function() {
			$("#EditResponse").load('ajax',$('#EditContent').serialize(),function(response,status,xhr){
				editor_postSave($.parseJSON(response));
			});
			return false;
		});
}

subEditMe_click = function() {
		whip_editingID = $(this).attr("id");
		$("div#whip_editor").stop(true, true).load('ajax','task='+whip_task+'&path='+escape(window.location.pathname)+escape(window.location.hash)+'&id='+whip_editingID+'&classes='+$(this).attr("class"),function(){
        editor_saveAction();
		});
		return false;
}

deleteMe_click = function() {
		var originalBorder = $(this).parent().css('border');
		$(this).parent().css('border','1px solid red');
		if(confirm('Are you sure you want to delete this and any other information associated with this content, including sub pages?')) {
		var deleteMeID = $(this).attr("id").replace('delete_cid_','');
		$("div#whip_editor").stop(true, true).load('ajax','task=delete_content&cid='+deleteMeID,function(){
        edit_sitemap();
		});
		} else {
		$(this).parent().css('border',originalBorder);
		}
		return false;
}

update_from_sitemap = function() {
	$("div#whip_editor").stop(true, true).load('ajax','task=update_from_sitemap&path='+escape(window.location.pathname)+escape(window.location.hash)+'&id='+whip_editingID+'&classes='+whip_editingClass,function(){
	       edit_sitemap();
	       set_preview_mode();
			});
}

edit_sitemap = function() {

		whip_task = 'edit_sitemap';
        whip_editingID = 'sitemap';
        whip_editingClass = 'sitemap';
		load_WhipScreen();
		whip_task = 'edit_content';
}

editor_postSave = function(response,status,xhr) {
		if(response) {
			$("#EditResponse").html('<span class="response_info">Saved! Loading preview... <img src="/templates/version1/css/images/ajax-loader.gif" align="absmiddle"/></span>');
			set_preview_mode(response['path']);
			if(whip_editingID.substr(0,6) == 'array_') {
				
				whip_editingID = whip_editingID.split('_pos_')[0].split('_cid_')[0].substr(6);
				var editReturn = load_WhipScreen();
			} else if(response['element'] == 'sitemap') {
				
				whip_task = 'edit_sitemap';
				var editReturn = function(){load_WhipScreen();whip_task = 'edit_content';}
			} else {
				var editReturn = function(){window.location.assign(response['path']);}
			}
			setTimeout(editReturn,2000);
			return false;
		}
}


goEditMode = function() {
	  $(".editable").hover(editMe_mouseover,editMe_mouseout);
	  $(".editable").click(editMe_click);
	  }

closeEditMode = function() {
	$("#whip_editor_box").remove();
	$(".whip_hover_box").remove();
	$(".editable").unbind('mouseenter',editMe_mouseover);
	$(".editable").unbind('mouseleave',editMe_mouseout);
	$(".editable").unbind('click',editMe_click);
}

setAjaxUploader = function() {
		for(i=0;i<fileUploads.length;i++) {
		var fu = fileUploads[i];
		$('#EditContent').after('<div id="uf_'+fu+'" style="position:absolute;"><input id="fu_'+fu+'" class="invisible" type="file" name="file" /></div>');
        $('#'+fu).mouseover(fileMove(fu));
        $('#'+fu).click(function(fu){fileBrowse(fu);return false;});
		$('#fu_'+fu).change(function() {
            $(this).upload('/whip/upload', function(res) {
            if(res['file_type'] == 'images') {
            	$('#label_'+fu).children('img').attr('src','/images/resized/thumb_'+res['file_name']);
            }
            $('#label_'+fu).children('span').html(res['file_name']);
            $('#input_'+fu).attr('value',res['id']);
            }, 'json');
        });
		}
}

function pageY(el) {
    var ot = 0;
    while (el && el.offsetParent != el) {
        ot += el.offsetTop ? el.offsetTop : 0;
        el = el.offsetParent;
    }
    return ot;
}

function pageX(el) {
    var ol = 0;
    while (el && el.offsetParent != el) {
        ol += el.offsetLeft ? el.offsetLeft : 0;
        el = el.offsetParent;
    }
    return ol;
}

function fileMove(handle) {
    if (navigator.appName == "Microsoft Internet Explorer") {
        return; // Don't need to do this in IE. 
    }
    var link = '#'+handle;
    var input = '#fu_'+handle;
    var editHeaderHeight = 50;
    var formLeftMargin = 5;
    var buttonHorizontalPadding = 10;
    var linkLoc = new Array();
        linkLoc[0] = $(link).width();
        linkLoc[1] = $(link).height();
        linkLoc[2] = $(link).parent().position();
        //$(this).prepend('<div class="whip_hover_box"><img class="whip_edit_button" src="/templates/version1/css/images/edit_button.png"/><div class="whip_highlight"></div></div>');
        $(input).css('position','absolute');
        $(input).css('width', parseInt(linkLoc[0])+buttonHorizontalPadding);
        $(input).css('height', parseInt(linkLoc[1]));
        $(input).css('top', parseInt(linkLoc[2].top)+editHeaderHeight);
        $(input).css('left',parseInt(linkLoc[2].left)+formLeftMargin);
}

function fileBrowse() {
    // This works in IE only. Doesn't do jack in FF. :( 
    var browseField = document.getElementById("fileupload");
    browseField.click();
}

whipitup = function() {

//Make Editor Top Bar
    
    if(getCookie('LoginID') != '') {
	var edit_mode = false;
	
	$("#edit_mode_toggle").click(function() {
		if(edit_mode) {
			$("#edit_mode_toggle").attr('class','');
			edit_mode = false;
			closeEditMode();
		} else {
			$("#edit_mode_toggle").attr('class','on');
			edit_mode = true;
			goEditMode();
		}
		return false;
	});
	$("#edit_sitemap").click(function() {
		
		edit_sitemap();
		return false;
	});
	
	}
}
