// Globals
var mdata;
var lala=0;
var geo = [];
var lastView='listview';

$('#dialog-message').hide();
$('#add_confirmation_dialog').hide();
/*Hiding the div with ID dialog-message and #confirmation_dialog
These 2 divs are responsible for the modal boxes .
*/
/*a Function to Initialise a Dialog instance for the modal box */
function modal_message()
{
$('#dialog-message').dialog({
	modal: true,
	buttons: {
			Ok: function() {
				$(this).dialog('destroy');
            }
	}
});
}
$(function() {
	$( ".column" ).sortable({
		disabled: true,
		connectWith: '.column'
});

	$( ".portlet" ).addClass( "ui-widget ui-widget-content ui-helper-clearfix ui-corner-all" )
	.find( ".portlet-header" )
	.addClass( "ui-widget-header ui-corner-all" )
	.prepend( "<span class='ui-icon ui-icon-minusthick'></span>")
	.end()
	.find( ".portlet-content" );

	$( ".portlet-header .ui-icon" ).click(function() {
		$( this ).toggleClass( "ui-icon-minusthick" ).toggleClass( "ui-icon-plusthick" );
		$( this ).parents( ".portlet:first" ).find( ".portlet-content" ).toggle();
	});
	$( ".column" ).disableSelection();
});

$(function() {
		$( "#accordion" ).accordion({
			fillSpace: true,
			collapsible: true
		});
});
$(document).ready(function() {
		$(function() {
		$( "#radiobutton" ).buttonset();
	});
});	

function guichanger_1(){
	gui_theme=$('#gui_selector').val();
	$("#theme_change" ).attr("href", 'css/'+gui_theme );
	$.post('getcontent.php',{switcharg : 'change_gui', gui_type: gui_theme}, function(m){
	
	},'html');
};

function userlogin(){ 
	var cus_type='customer';   
	// Add check of destinations, and confirmation box to decide reaction on each dest type
	var htmlcode='<form id=\'add_form\'><ul style=\'text-align:right;\'><li>username <input type=\'text\' name=\'username\' size=\'24\'></li><li>password <input type=\'password\' name=\'password\' size=\'24\'></li></ul></form>';
	$('span#add_confirmation_content').html(htmlcode);
	//-----------------------
	$('#add_confirmation_dialog').dialog({ /*Initialising a confirmation dialog box (with  cancel/OK button)*/
			autoOpen: false,
			width: 'auto',
			modal: true,
			buttons: {
						'Ok': function() { //If the user choose to click on \"OK\" Button
								data=$('#add_form').serialize();
 								$(this).dialog('close'); // Close the Confirmation Box
                       			$.ajax({//make the Ajax Request
									type: 'post',
									url: 'newauth.php',
									data: data,
									success: function(msg) {//if the page add.php returns the value \"OK\"
										msg=msg.replace(/<!DOCTYPE([^>]+)>/g,'');
										response=msg.substr(0,2);
										if(response=='OK'){
											msg=msg.substr(3);
											$('span#message_content').html(msg);
											// Add update to table to reflect changes
											window.location.replace('infopages/10000.php');
											modal_message();//Display the success message in the modal box
										}else {
	  										msg=msg.substr(1);
	  										$('span#message_content').html(msg);
	  										modal_message();//Display the Fail message in the modal box
										}
    								}
								});
               }, 
				'Cancel': function() { //if the User Clicks the button \"cancel\"
						$(this).dialog('close');
				} 
		}
	});
	$('#add_confirmation_dialog').dialog('open');//Display confirmation Dialogue when user clicks on \"delete Image\"
        	return false;
  };

function addcustomer(){ // if a user clicks on the \"add\" image
	var cus_type='customer';   
	// Add check of destinations, and confirmation box to decide reaction on each dest type
	$.post('customer_add_form.php',{switcharg : cus_type}, function(m){
				$('span#add_confirmation_content').html(m);
			},'html');
	//-----------------------
	$('#add_confirmation_dialog').dialog({ /*Initialising a confirmation dialog box (with  cancel/OK button)*/
			autoOpen: false,
			width: 'auto',
			modal: true,
			buttons: {
						'Ok': function() { //If the user choose to click on \"OK\" Button
						switch(cus_type){
						case 'restaurant':
						case 'cafe':
						case 'foodstore':
								data=$('#add_form').serialize();
 								$(this).dialog('close'); // Close the Confirmation Box
                       			$.ajax({//make the Ajax Request
									type: 'post',
									url: 'add.php',
									data: data,
									success: function(msg) {//if the page add.php returns the value \"OK\"
										msg=msg.replace(/<!DOCTYPE([^>]+)>/g,'');
										response=msg.substr(0,2);
										if(response=='OK'){
											msg=msg.substr(3);
											$('span#message_content').html(msg);
											// Add update to table to reflect changes
											modal_message();//Display the success message in the modal box
										}else {
	  										msg=msg.substr(1);
	  										$('span#message_content').html(msg);
	  										modal_message();//Display the Fail message in the modal box
										}
    								}
								});
                				break;
						
    						default:var data='';
    						break;
					}//Switch END
				}, 
				'Cancel': function() { //if the User Clicks the button \"cancel\"
						$(this).dialog('close');
				} 
		}
	});
	$('#add_confirmation_dialog').dialog('open');//Display confirmation Dialogue when user clicks on \"delete Image\"
        	return false;
  };
  
  function contactForm(switcharg){ // if a user clicks on the \"add\" image
		// Add check of destinations, and confirmation box to decide reaction on each dest type
	  switch (switcharg){
	  		case 'nysalg':
			  $.post('getcontent.php',{switcharg : 'fill_contact_form'}, function(m){
				  $('span#ui-dialog-title-add_confirmation_dialog').html('Send din henvendelse vedrørende '+switcharg);
					$('span#add_confirmation_content').html(m);
				},'html');
			  break;
	  		case 'kryssalg':
				  $.post('getcontent.php',{switcharg : 'fill_contact_form'}, function(m){
					  $('span#ui-dialog-title-add_confirmation_dialog').html('Send din henvendelse vedrørende '+switcharg);
						$('span#add_confirmation_content').html(m);
					},'html');
			   break;
	  		case 'motebooking':
				  $.post('getcontent.php',{switcharg : 'fill_contact_form'}, function(m){
					  $('span#ui-dialog-title-add_confirmation_dialog').html('Send din henvendelse vedrørende møtebooking');
						$('span#add_confirmation_content').html(m);
					},'html');
			   break;
	  		case 'winback':
				  $.post('getcontent.php',{switcharg : 'fill_contact_form'}, function(m){
						$('span#ui-dialog-title-add_confirmation_dialog').html('Send din henvendelse vedrørende '+switcharg);
						$('span#add_confirmation_content').html(m);
					},'html');
			   break;
	  		case 'leadsgenerering':
				  $.post('getcontent.php',{switcharg : 'fill_contact_form'}, function(m){
					  $('span#ui-dialog-title-add_confirmation_dialog').html('Send din henvendelse vedrørende '+switcharg);
						$('span#add_confirmation_content').html(m);
					},'html');
			   break;
	  		case 'kontakt':
				  $.post('getcontent.php',{switcharg : 'fill_contact_form'}, function(m){
					  $('span#ui-dialog-title-add_confirmation_dialog').html('Send din henvendelse');
						$('span#add_confirmation_content').html(m);
					},'html');
			   break;
	  		case 'rekvisita':
				  $.post('getcontent.php',{switcharg : 'rekvisita'}, function(m){
					  $('span#ui-dialog-title-add_confirmation_dialog').html('Send din bestilling/henvendelse vedr. rekvisita');
						$('span#add_confirmation_content').html(m);
					},'html');
			   break;
	  }
	  //-----------------------
		$('#add_confirmation_dialog').dialog({ /*Initialising a confirmation dialog box (with  cancel/OK button)*/
				autoOpen: false,
				width: 'auto',
				modal: true,
				buttons: {
						'Send': function() { //If the user choose to click on \"OK\" Button
								data=$('#add_form').serialize();
								$(this).dialog('close'); // Close the Confirmation Box
					   			$.ajax({//make the Ajax Request
									type: 'post',
									url: 'getcontent.php',
									data: 'switcharg=read_contact_form&'+data,
									success: function(msg) {//if the page add.php returns the value \"OK\"
										msg=msg.replace(/<!DOCTYPE([^>]+)>/g,'');
										response=msg.split('__________');
										if(response[0]=='OK'){
											$('span#message_content').html(response[1]);
											// Add update to table to reflect changes
											modal_message();//Display the success message in the modal box
										}else {
											$('span#message_content').html(response[1]);
											modal_message();//Display the Fail message in the modal box
										}
									}
								});
					}, 
					'Cancel': function() { //if the User Clicks the button \"cancel\"
							$(this).dialog('close');
					} 
			}
		});
		$('#add_confirmation_dialog').dialog('open');//Display confirmation Dialogue when user clicks on \"delete Image\"
	        	return false;
	  };
  function changegui(){ // if a user clicks on the \"add\" image
	  var gui_theme='redmond/jquery-ui-1.8.2.custom.css';
		// Add check of destinations, and confirmation box to decide reaction on each dest type
		$.post('getcontent.php',{switcharg : 'gui_selector'}, function(m){
					$('span#add_confirmation_content').html(m);
				},'html');
		//-----------------------
		$('#add_confirmation_dialog').dialog({ /*Initialising a confirmation dialog box (with  cancel/OK button)*/
				autoOpen: false,
				width: 'auto',
				modal: true,
				buttons: {
							'Ok': function() { //If the user choose to click on \"OK\" Button
								//	data=$('#add_form').serialize();
									gui_theme=$('input:radio[name=gui_type]:checked').attr('id');
									//return false;
								/*	data=data+'&switcharg=change_gui';
	 								$(this).dialog('close'); // Close the Confirmation Box
	                       			$.ajax({//make the Ajax Request
										type: 'post',
										url: 'getcontent.php',
										data: data,
										success: function(msg) {//if the page add.php returns the value \"OK\"
											msg=msg.replace(/<!DOCTYPE([^>]+)>/g,'');
											response=msg.substr(0,2);
											if(response=='OK'){
												msg=msg.substr(3);
												$('span#message_content').html(msg);
												// Add update to table to reflect changes
												modal_message();//Display the success message in the modal box
											}else {
		  										msg=msg.substr(1);
		  										$('span#message_content').html(msg);
		  										modal_message();//Display the Fail message in the modal box
											}
	    								}
									});*/
								//	$('span#message_content').html('gui changed');
								//	return false;
									// Add update to table to reflect changes
								//	modal_message();//Display the success message in the modal box
									$("#theme_change" ).attr("href", 'css/'+gui_theme );
									// How to avoid second form box???
									// Also need to store to mysql db the chosen gui type
									
	                }, 
					'Cancel': function() { //if the User Clicks the button \"cancel\"
							$(this).dialog('close');
					} 
			}
		});
		$('#add_confirmation_dialog').dialog('open');//Display confirmation Dialogue when user clicks on \"delete Image\"
	        	return false;
	  };

function viewmode(){
		var id = $('input:radio[name=viewtype]:checked').attr('id');
		if (lastView==undefined)lastView='listview';
		switch (id){
		case 'mapview':
				switch (lastView){
					case 'mapview':break;
					case 'listview':$('#listBar').hide();$('#map').appendTo('#content-left');$('#sideBar').appendTo('#content-right');$('#sideBar').show();break;
					case 'imageview':$('#imageBar').hide();$('#map').appendTo('#content-left');$('#sideBar').appendTo('#content-right');$('#sideBar').show();break;
				}
				break;
		case 'listview':
				switch (lastView){
					case 'mapview':$('#sideBar').hide();$('#listBar').appendTo('#content-left');$('#listBar').show();$('#map').appendTo('#content-right');break;
					case 'listview':break;
					case 'imageview':$('#imageBar').hide();$('#listBar').appendTo('#content-left');$('#listBar').show();break;
				}
				break;
		case 'imageview':
				switch (lastView){
					case 'mapview':$('#imageBar').appendTo('#content-left');$('#imageBar').show();$('#sideBar').hide();$('#map').appendTo('#content-right');break;
					case 'listview':$('#listBar').hide();$('#imageBar').appendTo('#content-left');$('#imageBar').show();break;
					case 'imageview':break;
				}
				break;
		}
		lastView=id;
		google.maps.event.trigger($('#map').data('bMap').map, "resize");// Resize map
		$('#map').data('bMap').map.setCenter( new google.maps.LatLng(geo[0],geo[1]));// Center map
	};
	
function loadmap(adr){
	var geocoder = '';
	geocoder = new google.maps.Geocoder();
	if (geocoder) {
		adr=adr.split(' ').join('+');
		geocoder.geocode({address: adr}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				var x=''+results[0].geometry.location;
				var y=x.replace(/[()]/g,'');
				geo=y.split(',');
				myLatlng = results[0].geometry.location;
				//$('#sideBar').html('');
				if (lala==0){
					lala=1;
					$('<div id=\'map\'>').appendTo('#content-right');
					$('<div id=\'listBar\'>').appendTo('#content-left');
					$('<div id=\'sideBar\'>').appendTo('#content-right');
					$.post('../getcontent.php',{switcharg:'geodata', radius : '200', lng : geo[0], lat : geo[1]}, function(m){
						//alert(m.extra[0]);
						//alert(m.extra[1]);
						var mdata=m.extra[0];
						var mlist=m.extra[1];
						var newvar='<script>var oTable = $(\'#listTable\').dataTable({\'bPaginate\': false,\'sScrollY\': \'230px\',\'bJQueryUI\': true});</script><table id=\'listTable\' cellspacing=\"1\" class=\"dataTable\" width=\'100%\' style=\'text-align:right\'><thead><tr><th></th><th>Address</th><th>info</th><th>Type</th></tr></thead><tbody>';
						for (x=0,len=mlist.list.length;x < len; x++){
							var newlist=mlist.list[x];
							newvar=newvar+'<tr><td><div style=\'float:left;width:120px\'>image...</div></td><td><div style=\'float:left;width:200px;text-align:left;line-height:13px\'><a href=\'infopages/'+newlist.customer_id+'.php?page='+newlist.customer_id+'&lastview=ListView\'>'+newlist.customer_name+'</a><br>'+newlist.address_1+' , '+newlist.postalcode+' '+newlist.postalplace+'<br><b>'+newlist.country+'</b></div></td><td><div style=\'float:left;width:200px\'>Div text about place ....</div></td><td><div style=\'float:left;width:100px\'>restaurant/cafe/foodstore..</div></td>';
						}
						newvar=newvar+'</tbody></table>';
						//alert(newvar);
						$('#listBar').html(newvar);
						map = $('#map').bMap({
			    			mapZoom: 14,
			    			mapCenter:[geo[0],geo[1]],
			    			mapSidebar:'sideBar', //id of the div to use as the sidebar
				    		markers:mdata
			    		});
					 },'json');
					$('#sideBar').hide();// Not working?
				}else{
					google.maps.event.trigger($('#map').data('bMap').map, "resize");// Resize map
					$('#map').data('bMap').map.setCenter( new google.maps.LatLng(geo[0],geo[1]));
				}
			}else{
	          	alert('Geocode was not successful for the following reason: ' + status);
			}
	   });
	}
	
};
