$(document).ready(function(){
  
  // setup country / province selector
  $('select.countrySelect').change(function(){
    
    getProvinces();
    
  });
  
  $('select.provinceSelect').change(function(){
    
    getCities();
    
  });
  
  // load presentations pager
  if($('#defaultPresWrap').length == 1)
  {
    getChiroPresHtml();
  }
  
});

/**
 * log function
 * 
 * @param   msg   The message to log
 * 
 */
function log(msg)
{
  // only log if console available
  if(window.console)
  {
    console.log(msg);
  }
}

/*
Navigates to a specific page

page    the page to forward to
*/
function gotoPage(page)
{
    window.location = page;
}

/*
Displays confirmation box for delete clicks

form_id		the form to submit
*/
function confirmDelete(form_id, message)
{
	var answer = confirm("Are you sure? " + '\n' + message);
	
	if(answer)
	{
		$('#'+form_id).submit();
	}
}

/*
  Makes the elements with the requested class draggable
*/
function makeDraggable(target_class)
{
  $('.'+target_class).draggable({
    'handle': $('.handle'),
    'revert': true,
    revertDuration: 1000,
		"snap": '.ui-droppable',
		"snapMode": "inner",
		'snapTolerance': 50
  });
}

/*
  Gets the default presentations for display in the chiro admin view
*/
function getChiroPresHtml(offset)
{
  $('#defaultPresWrap').load(
    'chiroPres/getChiroPres',
    {
      page: offset
    },
    function(){
      makeDraggable('defaultFrame');
    });
}

/*
  make presentations sortable
*/
function makeCustomPresSortable()
{
  // make presentations sortable
  $('div.customPres div.presFramesWrap').sortable({
  	'containment': 'parent',
  	'forcePlaceholderSize': true,
  	'placeholder': 'frameBoxDrag',
  	'opacity': 0.5,
  	update: function(e, ui){
      // alert($(this).sortable('serialize'));

  		$.post(
  		  'chiroPres/editSortOrder',
  		  $(this).sortable('serialize') + '&pres_id=' + $('div.customPres').attr('id'),
  		  function(data){
  		    
  		    $('#pres_frames_' + data).effect('highlight', {color: "#36AF47"}, 2000);
  		    
  		  },
  		  'text'
  		);
  	}
  });
}

/**
 * gets the list of provinces, or a text entry field
 */
function getProvinces()
{
  $.get(
    '/location/getProvinces',
    {country_id: $('select.countrySelect').val()},
    function(data){
      $('select.provinceSelect').html(data);
    },
    'html'
  );
}

/**
 * gets the list of cities for requested province
 */
function getCities()
{
  $.get(
    '/location/getCities',
    {province_id: $('select.provinceSelect').val()},
    function(data){
      $('select.citySelect').html(data);
    },
    'html'
  );
}
