var cookies = false;

$(document).ready(function(){

	if(typeof $.cookie !== 'undefined'){
		cookies = true;	
	}

//////////////////////////////////////////////////////////////////////
	if(cookies){
		// after all this, should probably save an "optimised" version of the cookie
		// may be able to combine some of this stuff
		// cycling through cookies has no order. cycling through page has order on page
	
		// NEED to take account of cookie having elements that page doesn't
		// - and this is just the start of the bulletproofing it needs
	
		// use PANEL_POSITIONS cookie to position panels correctly
		var panel_positions_from_cookie = read_cookie($.cookie('PANEL_POSITIONS'));
		
//		alert($.cookie('PAGE_SETTINGS'));
		//this is horrible, but for now, it's to get data from page_setings
		//var panels1 = $.cookie('PAGE_SETTINGS').match(/s:???:"????";s:2:"on";/g);
		
		// can just search this string to see if a panel should be on the page
		// unless it's empty of course, in which case, show defaults ?!
		// at the mo, can't show those not already on the page, but can
		// remove those on the page that shouldn't be.
		var panels_to_show = ""; 
		if($.cookie('PAGE_SETTINGS')) {
		  var start1 = $.cookie('PAGE_SETTINGS').lastIndexOf('{');
		  var end1 = $.cookie('PAGE_SETTINGS').indexOf('}');
		  panels_to_show = $.cookie('PAGE_SETTINGS').substring(start1+1,end1);
		}
//		alert(panels1);
//		var panels2 = panels1.replace(/;s:2:"on";/g,'');
//		alert(panels2);
//		var panels3 = panels2.replace(/s:\d+:"/g,'');
//		alert(panels3);
//		var panels4 = panels3.substring(0,panels3.length-1); 
//		alert(panels4); 
//		var panels = panels4.split('"');
					   
		
		//following doesn't work as "read_cookie" is only designed for cookies
		//in the format of variable/value pairs a=b;c=d etc.
		//var test_page_settings = read_cookie($.cookie('PAGE_SETTINGS'));
	
		var positions_from_cookie= new Array(3);
		var positions_from_page = new Array(3);
		var new_positions_from_page = new Array(3);
		var temporary_holder = new Array(3);
		var positions_directory = new Array();
		for (i=0; i <3; i++) {positions_from_cookie[i]=new Array();}
		for (i=0; i <3; i++) {positions_from_page[i]=new Array();}
		for (i=0; i <3; i++) {new_positions_from_page[i]=new Array();}
		for (i=0; i <3; i++) {temporary_holder[i]=new Array();}
	
		for(var panel in panel_positions_from_cookie){
		  var position = panel_positions_from_cookie[panel].split("-")[1];
		  var position_array = position.split(":");
		  var column = position_array[0];
		  var row = position_array[1];
		  positions_from_cookie[column-1][row] = panel;
		}
		
		// so far, we've created a 2d array of the cookie version of the positions.
		// now we need to compress it (ie, get rid of undefined elements.
	
		//count panel in each column
		for(col=1; col<=3; col++) {
		  col_panel_count = 0;
		  for(row=1; row<=positions_from_cookie[col-1].length; row++) {
			if(positions_from_cookie[col-1][row-1])
			{
				col_panel_count++;
			}
		  }
		  // do this for the number of panel in a columnn (needn't bother at all if this == number of rows)
		  // this copies a panel to the right place and deletes and preceeding blanks
		  for(row=1; row<=col_panel_count; row++) {
			if(!positions_from_cookie[col-1][row-1])
			{  
			  var row2=row+1;
			  emergency_brake=0;
			  while(!positions_from_cookie[col-1][row2-1] && emergency_brake < 100) {
				emergency_brake++;
				row2++;
			  }
			  positions_from_cookie[col-1][row-1] = positions_from_cookie[col-1][row2-1]; //copy content
			  positions_from_cookie[col-1][row2-1] = null; // destroy original
			}
		  }
		  // now remove the null values at he end of the column
		  var diff = positions_from_cookie[col-1].length-col_panel_count;
		  for(row=1; row<=diff; row++) {
			positions_from_cookie[col-1].pop();
		  }
		}		
		
		var old_column=0;
		var row = 0;
		$("div.panel_locked,div.panel").each(function () { /* needs to match up with selector in update_positions() below */
			row++;
			column=$(this).parents('.column').attr('id').split('-')[1];
			if(column != old_column) {
			  row = 1; // we're in a new column
			  old_column = column;
			}
	/*		$(this).css('border','2px solid green'); */
			positions_from_page[column-1][row-1] = $(this).attr('id');
	
			positions_directory[$(this).attr('id')] = [column-1, row-1];
		});


////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
/*		var cookie_page_output = "positions_from_cookie: \n";
		cookie_page_output = cookie_page_output + "---------------------------------\n";
		for(col=1; col<=positions_from_cookie.length; col++) {
			for(row=1; row<=positions_from_cookie[col-1].length; row++) {
				cookie_page_output = cookie_page_output + positions_from_cookie[col-1][row-1] + ' ; ';
			}
			cookie_page_output = cookie_page_output +'\n';
		}
		cookie_page_output = cookie_page_output + "---------------------------------\n\n";
		cookie_page_output = cookie_page_output + 'positions_from_page: \n';
		cookie_page_output = cookie_page_output + "---------------------------------\n";
		for(col=1; col<=positions_from_page.length; col++) {
			for(row=1; row<=positions_from_page[col-1].length; row++) {
				cookie_page_output = cookie_page_output + positions_from_page[col-1][row-1] + ' ; ';
			}
			cookie_page_output = cookie_page_output + '\n';
		}
		cookie_page_output = cookie_page_output + "---------------------------------\n\n";
		cookie_page_output = cookie_page_output + "panels_to_show: \n";
		cookie_page_output = cookie_page_output + "---------------------------------\n";
		cookie_page_output = cookie_page_output + panels_to_show + "\n";
		cookie_page_output = cookie_page_output + "---------------------------------\n\n";
		alert(cookie_page_output);*/
////////////////////////////////////////////////////////////////////////////////////
/////////////// There is a long pause after this is displayed. ///////////////////// 
/////////////// Need to look at optimising the code            /////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////

// -------------------------------------------------------------------------------------------------------------------	
// -------------------------------------------------------------------------------------------------------------------	
// -------------------------------------------------------------------------------------------------------------------	
// -------------------------------------------------------------------------------------------------------------------	

		///////////////////////////////////////////////////////////////////////////	
		// now comes the complex part. want to move the panels from the page layout
		// to the cookie layout in the minimum number of moves.
		///////////////////////////////////////////////////////////////////////////	
	
		// copy the "moved" panels to temporary_holder and delete the original from the page
		for(var i=0; i<positions_from_cookie.length; i++) {
		  for(var j=0; j<positions_from_cookie[i].length; j++) {
			if(positions_from_cookie[i][j] != positions_from_page[i][j]) { //only interested in those that are not the same on the page: 

		      var panel_name_end = positions_from_cookie[i][j].split('-')[1].toLowerCase();
			  var show_this_panel = false;
			  if(panels_to_show.indexOf(panel_name_end) != -1) {
			    show_this_panel = true
			  }
			  
			  if(positions_directory[positions_from_cookie[i][j]]) { // only do this if the panel is on the page
			    var page_positions = positions_directory[positions_from_cookie[i][j]];
				if(show_this_panel) {
//				  alert("moving "+ positions_from_page[page_positions[0]][page_positions[1]] +" to temporary holder");
			      temporary_holder[page_positions[0]][page_positions[1]] = $("#"+positions_from_page[page_positions[0]][page_positions[1]]).clone(true);
				}
			    $("#"+positions_from_page[page_positions[0]][page_positions[1]]).remove();
			  } else {
				// This is nowhere on the page, so I can't (at the moment) add this content, as I don't have it.
				// There will be lots of these in positions_from_cookie, as this cookie now has positions of all panels, whether they should be on page or not
				// However, some ought to be on the page, but are nowhere.
				if(show_this_panel) {
//			      alert(positions_from_cookie[i][j] + " doesn't exist on page (" + panel_name_end + ") BUT SHOULD");
// can/should potentially set some kind of flag here, or output something.
				} else {
			      //alert(positions_from_cookie[i][j] + " doesn't exist on page (" + panel_name_end + ") BUT IT'S NOT MEANT TO, SO ... COOL.");
				}
			  }
			  
			}
		  }
		}
		
		// move the "moved" panels to where the cookie says it should be
		for(var i=0; i<positions_from_cookie.length; i++) {
		  for(var j=0; j<positions_from_cookie[i].length; j++) {
			if(positions_from_cookie[i][j] != positions_from_page[i][j]) {
				
			  if(positions_directory[positions_from_cookie[i][j]]) { // only do this if the panel is on the page
			  
/*			    var page_positions = positions_directory[positions_from_cookie[i][j]];
			    destination_column_id = "column-" +  (i+1);
			    if(j==0) { // alert('adding ' + positions_from_cookie[i][j] + ' to start of column');
				  $("#"+destination_column_id).prepend(temporary_holder[page_positions[0]][page_positions[1]]);
			    } else { // alert('adding ' + positions_from_cookie[i][j] + ' after row ' + j);
				  // the following  adds the panel after "the row before it belongs" 
				  $("#"+positions_from_cookie[i][j-1]).after(temporary_holder[page_positions[0]][page_positions[1]]);
			    }
			    $("#"+positions_from_cookie[i][j]).css('border','2px solid blue');
*/ 
			    // replacing the above, as positions are incorrect given that some elements are
				// not to be displayed - FUNDAMENTAL issue is inconsistency between 2 cookies:
				// PAGE_SETTINGS and PANEL_POSITIONS .... must combine them ... like BBC site!!!
				
				// want to place this at position "j" (could be 0)
				// check if there is an element at j-1 (iterate), If so append after this element. Unless j-1 = 0, then prepend to column
				var page_positions = positions_directory[positions_from_cookie[i][j]]; // to find this element in temp_holder
				var destination_column_id = "column-" +  (i+1);
				var actual_j = j;
				while ((actual_j != 0) && !$("#"+positions_from_cookie[i][actual_j-1]).length) {
					actual_j = actual_j - 1;
				}
				if(actual_j==0) { // alert('adding ' + positions_from_cookie[i][j] + ' to start of column');
				  $("#"+destination_column_id).prepend(temporary_holder[page_positions[0]][page_positions[1]]);
			    } else { // alert('adding ' + positions_from_cookie[i][j] + ' after row ' + j);
				  // the following  adds the panel after "the row before it belongs" 
				  $("#"+positions_from_cookie[i][actual_j-1]).after(temporary_holder[page_positions[0]][page_positions[1]]);
			    }
			  }
			  
		    }
		  }
		}
		
		// remove any panels still on the page, but not in "show_this_panel"
		if(panels_to_show != "") {
		  var old_column=0;
		  var row = 0;
		  $("div.panel_locked,div.panel").each(function () { /* needs to match up with selector in update_positions() below */
			row++;
			column=$(this).parents('.column').attr('id').split('-')[1];
			if(column != old_column) {
			  row = 1; // we're in a new column
			  old_column = column;
			}
			new_positions_from_page[column-1][row-1] = $(this).attr('id');
		  });
		
		  var outstring="";
		  for(var i=0; i<new_positions_from_page.length; i++) {
		    for(var j=0; j<new_positions_from_page[i].length; j++) {
//		      outstring = outstring + "[" + new_positions_from_page[i][j] + "]"
			  var panel_name_end = new_positions_from_page[i][j].split('-')[1].toLowerCase();
//			  var show_this_panel = false;
			  if(panels_to_show.indexOf(panel_name_end) == -1) {
			    $("#"+new_positions_from_page[i][j]+".panel").remove(); //ie, don't remove those with class panel_locked
//		        $("#"+new_positions_from_page[i][j]).remove();
//			    show_this_panel = true
			  }
		    }
		  }
		}
//		alert(outstring);
	
// -------------------------------------------------------------------------------------------------------------------	
// -------------------------------------------------------------------------------------------------------------------	
// -------------------------------------------------------------------------------------------------------------------	
// -------------------------------------------------------------------------------------------------------------------	
	
		// use COLLAPSED cookie to toggle panels open/closed correctly
		// NEED this to also change the toggle collapsed/expanded button.
		// NEED this to also change the toggle collapsed/expanded button.
		// NEED this to also change the toggle collapsed/expanded button.
		// NEED this to also change the toggle collapsed/expanded button.
		// AND the number of feed headlines to output ???
		var collapsed_cookie_temp = read_cookie($.cookie('COLLAPSED'));
		$("div.panel-main").each(function () {
//			var parent_id_temp = $(this).parents('.panel').attr('id');
			var parent_id_temp = $(this).parents('.panel,.panel_locked').attr('id');
	
			if(collapsed_cookie_temp[parent_id_temp] == 1) {
				if($('#'+parent_id_temp+' div.panel-main').css('display') == 'block') {
					$(this).slideToggle('fast');
				}
			} else {
				if($('#'+parent_id_temp+' div.panel-main').css('display') == 'none') {
					$(this).slideToggle('fast');
				}
			}
		});
		
	}
	//////////////////////////////////////////////////////////////////////
	
//		$("#hack1").addClass("hack2");
		$("#features_data").addClass("hack2");

//		$('.panel form').submit(function(){
		$('.panel form.edit-panel-form').submit(function(){
		    var id = $(this).parents('.panel').attr('id');
			var ajax_options = {
				type: 			"POST",
				url: 			'/includes/ajax_callback_w.cfm',
				data: 			$(this).serialize(),
				success: 		function(data, textStatus){
								update_panel(data, textStatus, id);
								}
			};
			$.ajax(ajax_options);
			return false;
		});
	
		attach_number_of_feeds_event();
		
		/* fix IE bug - add active class with js */
		
/*		$('.top-panel-links').find('a:first').addClass('active');
			
		$('.top-panel-links a').mouseover(function(){
			if($(this).prev('img:hidden').length){
				var panel_id = $(this).parents('div.panel').attr('id'); 
				$('#'+panel_id+' a.active').removeClass('active');
				$(this).addClass('active');
				$('#'+panel_id+' .top-panel-links img:visible').hide();
				$(this).prev('img').show();
			}
		});*/
		
		/* edit panel */
		
		$('.edit-panel').click(function(){
			$(this).parents('.panel').find('div.panel-main').slideDown('fast');
			$(this).parents('.panel').find('form').slideToggle('fast');
			return false;
		});
		
		/* expand panel */
		
		$('.toggle-panel').click(function(){
			var img = $(this).children('img');
			$(this).parents('.panel,.panel_locked').find('div.panel-main').slideToggle('fast', function(){
				if(cookies){
				//remember in a cookie
//				var parent_id = $(this).parents('.panel').attr('id');
				var parent_id = $(this).parents('.panel,.panel_locked').attr('id');
				var collapsed_cookie = read_cookie($.cookie('COLLAPSED'));
					switch($('#'+parent_id+' div.panel-main').css('display')){
						case 'block':
						collapsed_cookie[parent_id] = 0;
						img.attr('src', '/images/redesign/furniture/minimise.gif');
						img.attr('height', 17);
						img.attr('width', 17);
						if(img.attr('alt').indexOf('maint') != -1) {
							img.attr('alt', 'Lleihau maint y Panel');
							img.attr('title', 'Lleihau maint y Panel');
						} else {
							img.attr('alt', 'Minimise Panel');
							img.attr('title', 'Minimise Panel');
						}
						break;
						
						case 'none':
						collapsed_cookie[parent_id] = 1;
						img.attr('src', '/images/redesign/furniture/maximise.gif')
						img.attr('height', 17);
						img.attr('width', 17);
						if(img.attr('alt').indexOf('maint') != -1) {
							img.attr('alt', 'Cynyddu maint y Panel');
							img.attr('title', 'Cynyddu maint y Panel');
						} else {
							img.attr('alt', 'Maximise Panel');
							img.attr('title', 'Maximise Panel');
						}
						break;
					}	
				write_cookie('COLLAPSED', collapsed_cookie); /* this may be setting the javascript variable, but not the COOKIE */
				}		
			});
			return false;
		});	
	
		$("div.column").sortable(
			{ 
				revert: true, 
				scroll: true,
				scrollSensitivity: 50,
				connectWith: ['.column'],
				placeholder: 'placeholder',
				handle: $('h2'),
				stop: update_positions,
				zIndex: 200,
				start: start_drag,
				appendTo: $('#container_div'),
				items: $('.panel')
			});
	
		$('#top-form form #cancel').click(function(){
			$('#top-form form').slideUp('fast');
		});
	
		$('#choose-colours label').click(function(){
			$('#choose-colours li.active').removeClass('active');
			$(this).parents('li').addClass('active');
		})
			
		$("#features > ul").tabs();
		
		if($('#customise_page img')){
			if($.browser.msie){
			$('#customise_page img').ifixpng(); 
//			$('#customise_page img').css('display', 'block'); /* make visible after fixing */
			}
		}

		// this makes the whole image a "button" in features (using href from first? a tag)
		$("div.fragment").hover(
		  function () {
			if(!($(this).hasClass('hovered'))) { $(this).addClass('hovered'); }
		  }, 
		  function () {
			if($(this).hasClass('hovered')) { $(this).removeClass('hovered'); }
		  }
		);
		$("div.fragment").find('img').click(
		  function () {
		    document.location = $(this).parent().find('a').attr('href');
		  }
		);
		
		// toggle "default" values in form elements (from DOM scripting)
		for (var i=0; i<document.forms.length; i++) {
		  var thisform = document.forms[i];
		  resetFields(thisform);
		}

});
		
///////////////////////////////////////////////////////
///////////////////// functions ///////////////////////
///////////////////////////////////////////////////////
function resetFields(whichform) {
  for (var i=0; i<whichform.elements.length; i++) {
	var element = whichform.elements[i];
	if (element.type == "submit") continue;
	if (!element.defaultValue) continue;
	element.onfocus = function() {
	  if (this.value == this.defaultValue) {
		this.value = "";
	  }
	}
	element.onblur = function() {
	  if (this.value == "") {
		this.value = this.defaultValue;
	  }
	}
  }
}

function start_drag(e, ui){
	if($.browser.msie){
		var margin = $(document).scrollTop()+20;
		ui.helper.css('margin-top', margin+'px');	
	}	
}

function update_positions(e, ui){
	if(!cookies){
		return true;
	}
	var panel_positions = read_cookie($.cookie('PANEL_POSITIONS'));
	var moved_panel_id = ui.item.attr('id');
	var moved_to_column_id = ui.item.parents('.column').attr('id');
	var order_in_column = 0;
//	$('#'+moved_to_column_id+' .panel:not(.ui-sortable-helper)').each(function(){
// following uses feature of jquery to have 'panel_locked's before 'panel's. Without this feature, order in statement below would be irrelevent.
/*	$('#'+moved_to_column_id+' .panel_locked:not(.ui-sortable-helper),#'+moved_to_column_id+' .panel:not(.ui-sortable-helper)').each(function(){ 
		var panel_id = $(this).attr('id');
		panel_positions[panel_id] = moved_to_column_id+':'+order_in_column;
		alert('panel_positions['+panel_id+'] = '+ moved_to_column_id +':'+ order_in_column);
	    order_in_column++;
	})*/
    for(i=1;i<=3;i++) {
	order_in_column = 0;
	moved_to_column_id = "column-" + i;
//	$('#'+moved_to_column_id+' .panel_locked:not(.ui-sortable-helper),#'+moved_to_column_id+' .panel:not(.ui-sortable-helper)').each(function(){ 
	$('#'+moved_to_column_id+' .panel_locked,#'+moved_to_column_id+' .panel').each(function(){ 
		var panel_id = $(this).attr('id');
		panel_positions[panel_id] = moved_to_column_id+':'+order_in_column;
//		alert('panel_positions['+panel_id+'] = '+ moved_to_column_id +':'+ order_in_column);
	    order_in_column++;
	})
	}
	write_cookie('PANEL_POSITIONS', panel_positions);
}

function read_cookie(cookie){
	var cookie_array = new Array();
	if(cookie){
	var cookie_elements = cookie.split(';');
		for(i=0;i<=cookie_elements.length;i++){
			if(cookie_elements[i]){
				cookie_data = cookie_elements[i].split('=');
				var key = cookie_data[0];
				cookie_array[key] = cookie_data[1];
			}
		}
	}
	return cookie_array;
}

function write_cookie(name, cookie_array){
	var cookie_str = '';
	for (key in cookie_array){
		cookie_str += key+'='+cookie_array[key]+';';	
	}
//	$.cookie(name, cookie_str);
//	$.cookie(name, cookie_str, { expires: 7, path: '/', domain: 'www.wrexham.gov.uk', secure: false });
	$.cookie(name, cookie_str, { expires: 7, path: '/', secure: false });
}

function attach_number_of_feeds_event(){
	$('div.feed-top a').unbind('click');
	$('div.feed-top a').click(function(){
		if(cookies){
			feed_limits_cookie = read_cookie($.cookie('FEED_LIMITS'));	
		}
		var id = $(this).parents('.feed').attr('id');
		var current_limit = $('#'+id+' li:visible').length;
		switch($(this).attr('class')){
		case 'add':
			$('#'+id+' li:hidden:first').show();
			current_limit ++;
			break;
		case 'remove':
			$('#'+id+' li:visible:last').hide();
			current_limit --;
			break;
		}
		feed_limits_cookie[id] = current_limit;
		if(cookies){
			write_cookie('FEED_LIMITS', feed_limits_cookie);	
		}
	return false;
	});
}

function update_panel(data, textStatus, id){
	$('#'+id+' .feed-output').html(data);
	$('#'+id+' form.edit-panel-form').slideUp();
	//reattach the events -> without this, acts strange in IE6 !?
	attach_number_of_feeds_event();	
}

