var id, entry_id, page;
jQuery(document).ready(function(e) {
	//get the master variables used when updating an entry
	id = jQuery('#id').val(), entry_id = jQuery('#entry_id').val(), page = jQuery('#page').val();
	//settup any handling on change of values in the entry form
    jQuery('form.entry input, form.entry select, form.entry textarea').change(function(e) {
		//vget the value of the item being changed
		var value = jQuery(this).val();
		//If it is a checkbox there are additonal checks to be done
		if( jQuery(this).attr('type') == 'checkbox' || jQuery(this).hasClass('checkbox') ){
			//If it is under a div called opt then it is a checbox group so need to group them
			if(jQuery(this).parent('.opt').size() > 0){
				//Create a tempary array
				var tmpArray = new Array();
				//If this item is being checked then add to array
				if(jQuery(this).is(':checked')){
					tmpArray[tmpArray.length] = jQuery(this).val();
				}
				//Loop thrugh all the siblings to this parent which are opts
				jQuery(this).parent('.opt').siblings('.opt').each(function(index, element) {
					//If the chekbox under this siblin is ticked add to temp array
					//Checked using size to stop doupbe selection issue overloading js
					if(jQuery(this).children(':checked, input[type=text]').size() > 0){
                   		tmpArray[tmpArray.length] = jQuery(this).children(':checked, input[type=text]').val();
					}
                });
				if(jQuery(this).hasClass('checkbox')){
					tmpArray[tmpArray.length] = jQuery(this).val();
				}			
				
				//Impload using commers to build the final list
				value = tmpArray.join(',');
			} 
			else if(!jQuery(this).is(':checked')){
				//If standard checkbox and not checked then set value to 0
				value = '0';
			}
		}
		else if( jQuery(this).attr('type') == 'text'){
			//now check if it is a group checkbox
			if(jQuery(this).parent('.group').size() > 0){
				if(jQuery(this).val().indexOf(',') != '-1'){
					alert("This field cant contain a commer");	
				}
				var tmpArray = new Array();
				jQuery(this).parent('.group').parent('.textGroup').parent().find('input').each(function(index, element) {
                    tmpArray[tmpArray.length] = jQuery(this).val();
                });
				value = tmpArray.join(',');
			}
		}
		//Build the data string that will be sent to be stored in the database
    	var data = {'id':id,'entry_id':entry_id,'question':jQuery(this).attr('name'),'value':value,'page':page};
		//Post to the server
		jQuery.post('/ajax/save_entry.php', data, function(result){
			//If the result is not a sucess then alert what has happend
			//Additonal handling for different types of errers done in save_entry
			if(result!='sucess'){alert(result);}
		});
    });
});
