/*********************************************************


	Copyright Sudbury Metis Council - 2009
	Author: Michael Connors
	Date: May 2009
	Contact: michael.connors@inbox.com


************************************************************/

/* list of all the panels in the smc document. This is for HIDEing and SHOWing divs */
var left	=	'#headlines_wrapper,#admin_menu_wrapper';
var right	=	'#home,#framework,#news,#contact,#admin,#main,#main_error,#password_confirm,#photos';
var both	=	left+','+right;

var main_display	='#main';
var error_display	='#main_error';
var nav_display='#headlines_wrapper';
$.blockUI.defaults.fadeOut = 200; 

/* ***********************************************
 *
 *	Load_HTML_Content - 
 *			  load an html page - no processing
 *
 *  view		= string of the page name in the view
 *  resultid	= string form id where to display the results
 *
 *****************************************************/
function load_content(view, resultid, errorid) {
	if(resultid==null) {
		var resultid='#main';
	}
	if(resultid==null) {
		var errorid='#main_error';
	}

	loading_block('Loading...', '#main', 1);
	var url=base_url+'load_page/'+view;
	$.get(url, { }, 
		function(pdata){
			if (pdata.header=='success')
			{

				//$("#content_panel").html('');
				$(resultid).html(pdata.content);
				show_id(resultid);
				//alert ("data:\n"+pdata.content);
			}
			else if (pdata.header=='error')
			{
				$(errorid).html(pdata.content);
				show_id(new Array(errorid,resultid));
			}
			else {
				
				alert ("Loading Page: "+page+" FAILED!");
			}
		}, 
		"json"
	);
	return false;
}

/* ***********************************************
 *
 *	Check Admin - User is Logged In?
 *
 *  return the NAV and MAIN admin home pages or FAIL
 *
 *****************************************************/
function check_admin() {
	var main_display='#main';
	var nav_display='#admin_menu_wrapper';
	var panel=new Array();
	//loading();
	loading_block('Checking...', main_display, 1);
	var url=base_url+'check_admin';
	$.get(url, { }, 
		function(pdata){
			if (pdata.header=='success')
			{
				if(pdata.results!=false) {
					$(main_display).html(pdata.results);
					panel.push(main_display);
				}
				if(pdata.leftpanel!=false) {
					$(nav_display).html(pdata.leftpanel);
					panel.push(nav_display);
				}
				init_admin_menu();
				show_id(panel);
			}
			else if (pdata.header=='fail')
			{
				load_content('admin_login');
			}
			else {
				
				alert ("Loading Page: "+page+" FAILED!");
			}
		}, 
		"json"
	);	
	
}

/* ***********************************************
 *
 *	Edit - edit a news record or People record
 *
 *  id - string id of the record number
 *	f	- string of the function to call
 *	type - string value referencing id number in peopletype table
 *
 *  return - json format of the form
 *
 *****************************************************/
function edit(f,id,type) {

	//alert("Sending news_edit("+id+")");
	var options = { 
		url: base_url+f+'/'+id+'/'+type, 
		type: 'get',
		dataType: 'json',
		success: function (data) {
						if (data.header=='success')
						{
							if(data.results!== undefined)
							{
								//alert("results response recived\n"+data.results);
								$(main_display).html(data.results);
								show_id(main_display);
							}
							else if (data.error!== undefined)
							{
								/* if ther is now results or nav then there is an error */
								$(error_display).html(data.error);
								show_id(error_display);
							}
						}
						else {
							alert ("Javascript Error: news_edit was NOT sucessfull\n"+data);
						}
						//showResponse(data, statusText, display_panel);  // post-submit callback
						//alert("pg: "+pg+"\npg.search(/search/i): "+pg.search(/search/i));
					},
		beforeSubmit: function(formData) {
						//alert("sending data...\nUrl:"+base_url+f+'/'+id);
						loading_block('Loading...', '#main', 1);
						//showRequest(formData,null,options);
					},
		timeout:	3000
    }; 
					//alert("2- sending data...\nUrl:"+base_url+pg+"\nleftp= "+leftp+"\nformid= "+formid);
	$(this).ajaxSubmit(options);
	
}

/* ***********************************************
 *
 *	Del - delete a news record
 *
 *  id - string id of the record number
 *  offset - number for the staring postion of the list
 *	f	- string of the function to call
 *	peopletype - used to make the reditect call to get a for list
 *
 *  return - json format of confirmation
 *
 *****************************************************/
function del(f,id,offset,peopletype) {

	//alert("deleting: "+f+" , "+id+" , "+offset+" , "+redirect);
	var options = { 
		url: base_url+f+'/'+id+'/'+peopletype, 
		type: 'get',
		dataType: 'json',
		success: function (data) {
						if (data.header=='success')
						{
							if(data.results!== undefined)
							{
								//alert("results response recived\n"+data.results);
								loading_block(data.results, main_display, 2, 2000);
								//alert("redirecting: "+redirect);
								if (data.redirect!==undefined)
								{	var arg = false;
									if(data.argument!==undefined){ arg=data.argument; }
									var t = setTimeout(function(){ process(data.redirect, main_display, false, offset, arg ); }, 1000);
								}
							}

						}
						else {
							alert ("Javascript Error: news_delete was NOT sucessfull\n"+data);
						}
					},
		beforeSubmit: function(formData) {

						if(confirm("Are you sure you want to delete this record?\n\nDeleting a record cannot be undone.")) {
							loading_block('Deleting...',main_display,1);
						}
						else {
							return false;
						}
					},
		timeout:	5000
    }; 
					//alert("2- sending data...\nUrl:"+base_url+pg+"\nleftp= "+leftp+"\nformid= "+formid);
	$(this).ajaxSubmit(options);
	
}

/* ***********************************************
 *
 *	loading - Hide left or right or both panel content DIVs
 *            and show the loading graphic
 *
 *	panel_loc - 'left', 'right', 'both', default=right
 *
 *	http://malsup.com/jquery/block/
 *
 *****************************************************/
function loading_block(msg, panel, state, delay) {
	if(state===undefined) {
		state=1;
	}
	if(panel===undefined) {
		panel=main_display;
	}
	if(delay===undefined) {
		delay=2000;
	}

	if (state==1)
	{
		$(panel).block({ 
		message:  '<h4 id="notice"> '+msg+'</h4>',
		showOverlay: true,
		fadeIn:  200,
		fadeOut:  200,
		timeout: 10000,
		/* timeout: 10000,  */
		css: { 
			width:          '70%', 
			top:            '50%', 
			border: 'none', 
			padding: '2px', 
			backgroundColor: '#A2A27F', 
			'-webkit-border-radius': '5px', 
			'-moz-border-radius': '5px', 
			opacity: 1.5, 
			color: '#fff' 
		},
		overlayCSS:  { 
	        opacity:         0 
		}
		});
	}
	else if (state==2)
	{
		$('#notice').html(msg);
		//var exec = "loading_block('','"+panel+"',0)";
		//alert (exec);
		var t =setTimeout(function() { $(panel).unblock();}, delay); 
	}
	else 
	{
		$(panel).unblock();
	}

}


/* ********************************************************
 *
 *	SHOW_ID - show a page id.
 *				If the ID is on the right then hide all right panels
 *				If the ID is on the left then hide all left panels
 *
 *	pageid - array of string values or single string of div id
 *	
 **********************************************************/
function show_id(pageid) {
	/*find out which pages are being shown and then clear the left or right panels */
	var panelLeft=0;
	var panelRight=0;
	if (is_array(pageid))
	{
		// Loop over each value in the array.
			$.each(
				pageid,
				function( intIndex, objValue ){
					//alert("Checking Array for Page to show. Next: "+objValue);
					if(left.indexOf(objValue)>-1){
						//alert(objValue+" is in the Left Panel.");
						panelLeft=1;
					}
					else if(right.indexOf(objValue)>-1){
						//alert(objValue+" is in the Right Panel.");
						panelRight=1;
					}
				}
			);
			// hide all the panels first
			if(panelLeft) {
				$(left).hide();
			}
			if(panelRight) {
				$(right).hide();
			}
			$.each(	pageid,	function( intIndex, objValue ){ $(objValue).show();	});
	}
	else {
		if(left.indexOf(pageid)>-1){
			//alert(pageid+" is in the Left Panel!");
			$(left).hide();
			panelLeft=1;
		}
		else if(right.indexOf(pageid)>-1){
			//alert(pageid+" is in the Right Panel!");
			$(right).hide();
			panelRight=1;
		}
		//alert("Showing Page: "+pageid);
		$(pageid).show();
	}
	//$('div.loading').unblock();
	loading_block('Done.', main_display, 2, 2000);
}


/************************************************
 *
 * Show/Hde password confirm in people edit form
 *
 *	1- show
 *	2- hide
 *
 ************************************************/
 function pwd_confirm(state){
	 //alert((state==1));
	 if(state==1) {
		 $('#p_label,#c_label,#pc_pwd,#pc_confirm').show();
	 }
	 else {
		 $('#p_label,#c_label,#pc_pwd,#pc_confirm').hide();
	 }
 }


/************************************************
 *
 * Show/Hde 'Send Approval' in the news edit form
 *
 *	1- show
 *	2- hide
 *
 ************************************************/
 function show_approval(state){
	 //alert((state==1));
	 if(state==1) {
		 $('#approve_label,#approve_checkbox,#approve_names').show();
	 }
	 else {
		 $('#approve_label,#approve_checkbox,#approve_names').hide();
	 }
 }

/* ***********************************************
 *
 *	Submit forms
 *
 *  page = string of url page to call or function in controller
 *  leftpanel = the results of the form will need the div id of the left panel
 *  btn	 = string of button id
 *  fromid = string of the form id
 *
 *  http://malsup.com/jquery/form/#options-object
 *
 *****************************************************/
 //'people_save','save_form_".$row['type']."', 'false', '#custom_error', 'false'
function form_submit(pg, formid, leftp, errorp) {
	//var main_display='#main';
	//var nav_display='#headlines_wrapper';
	//var error_display='#main_error';

	if(errorp!='false' && errorp!=null && errorp!==undefined) {
		error_display=errorp;
	}
	//alert("error: "+error_display);
	if(leftp!='false' && leftp!=null && leftp !==undefined) {
		nav_display=leftp;
	}
	var panel=new Array();

	//var queryString = $(formid).formSerialize();
	//alert("Submitting form: "+formid+"\n"+queryString);
	
	var options = { 
		url: base_url+pg, 
		type: 'post',
		dataType: 'json',
		success: function (data) {
						//alert("ok... now showResponce");
						//alert("page ...: "+pg);
						if(data.results!==undefined || data.leftpanel!==undefined)
						{
							if(data.results!==undefined) {
								//alert("results response sent");
								$(main_display).html(data.results);
								panel.push(main_display);
							}
							if(data.leftpanel!==undefined) {
								//alert("nav response sent");
								$(nav_display).html(data.leftpanel);
								panel.push(nav_display);
							}
							show_id(panel);
							//alert(formid);
							if (formid.search(/loginform/)>-1) {
								init_admin_menu();
							}
						}
						else {
							loading_block(data.error, main_display, 2, data.delay);
							if (data.redirect!==undefined)
							{	var arg = false;
								if(data.argument!==undefined){ arg=data.argument; }
								var t = setTimeout(function(){ process(data.redirect, main_display, false, '0', arg ); }, 1000);
							}
						}

						if (data.js_eval!==undefined)
						{
							eval(data.js_eval);
						}
						//showResponse(data, statusText, display_panel);  // post-submit callback
						//enable_btn(btn);
						//alert("pg: "+pg+"\npg.search(/search/i): "+pg.search(/search/i));
						if(formid.search(/search_form/i)>-1) {
							//alert("data.results.search(/display_controls/i): "+data.results.search(/display_controls/i));
							if (data.results.search(/display_controls/i)>-1 ){
								init_slider(true);
							}
							else {
								init_slider(false);
							}
						}
					},
		beforeSubmit: function(formData) {
						//showRequest(formData,null,options);
						//alert("sending data...\nUrl:"+base_url+pg+"\nleftp= "+leftp+"\nformid= "+formid);
						loading_block('Sending Data...', main_display, 1);
						//disable_btn(btn);
						
					},
		timeout:	3000
    }; 
					//alert("2- sending data...\nUrl:"+base_url+pg+"\nleftp= "+leftp+"\nformid= "+formid);
	$(formid).ajaxSubmit(options);
}


function showRequest(formData, jqForm, options) { 
    // formData is an array; here we use $.param to convert it to a string to display it 
    // but the form plugin does this for you automatically when it submits the data 
    var queryString = $.param(formData); 
    alert('About to submit: \n\n' + queryString+"\nPageName: "+options.url); 
    return true; 
}
/* ***********************************************
 *
 *	Process - get page from controller and 
 *            display the results in a div
 *
 *  func		= string function in controller
 *	main		= string of DIV id where the main results to be displayed
 *  secondary	= string of DIV id where the seconday panel results to be displayed
 *  arg(n)			= optional arguments
 *
 *  http://malsup.com/jquery/form/#options-object
 *
 *****************************************************/
 //process('news_list', '#main', false, '6')
function process(func, main, secondary, arg1, arg2) {
	var argument1=false;
	var argument2=false;

	if (main!==undefined  && main!==false)
		main_display=main;
	if (secondary!==undefined && secondary!==false)
		nav_display=secondary;
	if (arg1!==null && arg1!==false && arg1!==undefined) {
		argument1=arg1;
	}
	if (arg2!==null && arg2!==false && arg2!==undefined) {
		argument2=arg2;
	}
	var panel=new Array();
	loading_block('Processing...', main_display, 1);

	//alert("Func: "+func+"\nMain Display: "+main_display+"\nSecondary Display: "+nav_display+"\nArg 1: "+argument1+"\nArgument 2: "+argument2+"\nURL: "+base_url+func+'/'+argument1+'/'+argument2);

	var options = { 
		url: base_url+func+'/'+argument1+'/'+argument2, 
		type: 'get',
		dataType: 'json',
		success: function (data) {
						if (data.header=='success')
						{
							if(data.error===undefined) {
								data.error="Processing...";
							}
							loading_block(data.error, main_display, 2, 2000);

							if(data.results!==undefined)
							{
								//alert("data.results returned:\n"+data.results);
								$(main_display).html(data.results);
								panel.push(main_display);
							}
							if(data.leftpanel!==false && data.leftpanel!==undefined) {
								//alert("data.leftpanel returned:\n"+data.leftpanel);
								$(nav_display).html(data.leftpanel);
								panel.push(nav_display);
							}
							//alert("results response recived\n"+data.results);
							if ( func.search(/logout/i)>-1 )
							{
								panel.push('#headlines_wrapper');
							}
							show_id(panel);

							if(func.search(/search/i)>-1) {
								//alert("data.results.search(/display_controls/i): "+data.results.search(/display_controls/i));
								if (data.results.search(/display_controls/i)>-1 ){
									init_slider(true);
								}
								else {
									init_slider(false);
								}
							}

						}
						else {
							alert ("Javascript Error: "+func+" was NOT sucessfull\n"+data);
						}
					},
		timeout:	5000
    }; 
	$(this).ajaxSubmit(options);
	return false;
	
}

/* ***********************************************
 *
 *	Story - display a news story in the main panel
 *
 *  nid		= string id of the news record
 *
 *****************************************************/
function story(nid) {
	var main_display='#main';
	loading_block('Loading...', '#main', 1);
	var url=base_url+'story';
	$.post(url, { id: nid }, 
		function(data){
			if (data.header=='success')
			{
				$(main_display).html(data.content);
				show_id(main_display);
			}
			else {
				alert ("Javascript Error: story() was NOT sucessful.\nNews ID:"+nid+"\nUrl:"+url+"\nPlease contact the Adminstrator or try again."+data);
			}
		}, 
		"json"
	);
	return false;
}

/* ***********************************************
 *
 *	init_headlines - Initialize the moving headline Div
 *  http://malsup.com/jquery/cycle/options.html
 *
 *****************************************************/
function init_headlines() {
	//alert("init_headlines");
	show_id('#headlines_wrapper', false);
	$('#headlines').cycle({
				fx: 'scrollUp',
				timeout: 10000,
				speed:  2500,
				delay:  -1000,
				pause: 1,
				cleartypeNoBg: true,
				sync: 0
			});
}

/* ***********************************************
 *
 *	init_menu - Initialize the header menu Div
 *  http://www.gmarwaha.com/blog/2007/08/23/lavalamp-for-jquery-lovers/
 *
 *****************************************************/
function init_header_menu() {
	$("#menu").lavaLamp({
		fx: "backout",
		speed: 700,
		click: function(event, menuItem) {
				return false;
		}
	});
}

/* ***********************************************
 *
 *	jQuery Menu
 *
 *	http://www.i-marco.nl/weblog/
 *
 *****************************************************/
function init_admin_menu() {
  $('#admin_menu ul').hide();
  $('#admin_menu ul:first').show();
  $('#admin_menu li a').click(
    function() {
      var checkElement = $(this).next();
      if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
        return false;
        }
      if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
        $('#admin_menu ul:visible').slideUp('fast');
        checkElement.slideDown('fast');
        return false;
        }
      }
    );
}

/* ***********************************************
 *
 *	init_slider - Initialize the search results slider Div
 *  http://cssglobe.com/post/4004/easy-slider-15-the-easiest-jquery-plugin-for-sliding
 *
 *****************************************************/
function init_slider(controls) {
	if(controls==true) {
		$("#slider").easySlider({
			prevText: 'Previous',
			nextText: 'Next',
			firstShow: true,
			lastShow: true,
			controlsBefore:	'<div id="controls">',
			controlsAfter:	'</div>',
			vertical: true,
			continuous: true,
			speed: 500
		});
	}
	else {
		$("#slider").easySlider({
			controlsShow: false,
			vertical: true,
			continuous: true,
			speed: 500
		});
	}
}


function is_array(o) {
	return !(o.constructor.toString().indexOf("Array") == -1);
}


$(document).ready(function(){
	show_id('#home');
	init_headlines();
	init_header_menu();


	$("a[rel^='prettyPhoto']").prettyPhoto({
		animationSpeed: 'fast', /* fast/slow/normal */
		padding: 40, /* padding for each side of the picture */
		opacity: 0.5, /* Value betwee 0 and 1 */
		showTitle: false, /* true/false */
		allowresize: true, /* true/false */
		counter_separator_label: ' of ', /* The separator for the gallery counter 1 "of" 2 */
		theme: 'light_rounded', /* light_rounded / dark_rounded / light_square / dark_square */
		callback: function(){}
	});
});
