/* AJAX stuffs */

function abortAjax() {
  if (ajaxobj && ajaxobj != null) {
    ajaxobj.abort();
  }
}
function handleAjaxResponse(responseText) {
  if (responseText != null) {
    document.getElementById(reload_section_id).innerHTML = responseText;
    historyStorage.put(reload_section_id, responseText);
  } else {
    alert('There was a problem with the request.');
  }
}
function setSectionHtml(id, html) {
  if (document.getElementById(id) != null) {
    document.getElementById(id).innerHTML = html;
	}

}
function handleBackButton(reload_section_id) {
  if (historyStorage.get(reload_section_id) != null) {
    if (document.getElementById(reload_section_id) != null) {
      document.getElementById(reload_section_id).innerHTML = historyStorage.get(reload_section_id);
    }
  }
}
function reloadSection(sectionName, url, params) {
  reload_section_id = sectionName;
  if (params == null) {
    params = '';
  }
  $.post(url, params, function (data) {
    handleAjaxResponse(data);
  });
  $('#'+sectionName).effect('highlight',{},1000);
}
function reloadSectionAndWait(sectionName, url, params) {
  /*reload_section_id = sectionName;
  if (params == null) {
      params = '';
  }
  ajax.updates(url+"?"+params, handleAjaxResponse, sectionName);*/
  reloadSection(sectionName, url, params); // Not sure about original intent of this function
}
function reloadSectionWithForm(sectionName, form, url) {
  reload_section_id = sectionName;
  if (url == null) {
    url = form.action;
  }
  $(form).unbind('submit').submit(function() {
    $.post(
      url,
      $(form).serialize(),
      function(data) {
        handleAjaxResponse(data);
      });
    return false;
  });
  $(form).submit();
  $('#'+sectionName).effect('highlight',{},1000);
}
function reloadSectionWithFormAndWait(sectionName, form, url) {
  /*reload_section_id = sectionName;
  if (url == null) {
      url = form.action;
  }
  ajax.submitfs(url, form, handleAjaxResponse);*/
  reloadSectionWithForm(sectionName, form, url);
}
function ajaxHandleBackButton() {
	dhtmlHistory.initialize();
	dhtmlHistory.addListener(historyChange);
	for (var i=0;i<document.getElementsByTagName('*').length;i++) {
	  var id = document.getElementsByTagName('*')[i].id;
	  if (fnStartsWith(id, "ajax_")) {
		var element = document.getElementsByTagName('*')[i];
		handleBackButton(element.id);
	  }
	}
}
function historyChange() {
}
/* AJAX stuffs ends here */

/* Utilities */
function showInfo(id){
  e = $('#e-'+id+'');
  if (e) e.hide(); 
  i = $('#i-'+id+'')
  if (i) i.show();
}
function hideInfo(id){
  e = $('#e-'+id+'');
  if (e) e.show(); 
  i = $('#i-'+id+'')
  if (i) i.hide();
}
function resetDefaultInput(id, val) {
  var e = $('#'+id);
  if (!e)
    e = $(id);
  if (!e)
    return;
  if (e.val() == val)
    e.val('');
}
// function parameters are: 
// field - the string field, count - the field for remaining characters number and max - the maximum number of characters
function CountLeft(field, count, max) {
  // if the length of the string in the input field is greater than the max value, trim it
  if (field.value.length > max)
    field.value = field.value.substring(0, max);
  else
    // calculate the remaining characters
    count.value = max - field.value.length;
}

function go() {
}

/*function submitForm(parentForm, thisForm) {
 setTimeout("submitFormHelper('"+parentForm+"','"+thisForm+"')", 0);
 return false;
}

function submitFormHelper(parentForm, thisForm) {
  frm = document.getElementById(thisForm);
  win = window.opener;

  try { if (win) win.document.getElementById(parentForm).submit(); } catch (err) {} // ignore error 

  div = document.createElement('div');
  div.id = 'tmp_'+Math.random();
  frm.appendChild(div);
  reloadSectionWithFormAndWait(div.id, frm);

  try { if (win) win.location = win.location; } catch (err) {} // ignore error 

  window.close();
}*/

function initJQDatepicker(id) {
  $("#"+id).datepicker({changeMonth: true, changeYear: true});
  $("#"+id+"_date").click(function() { $("#"+id).datepicker("show"); });
}

function initJQDatepickerEuropean(id, isCms) {
  $("#"+id).datepicker({changeMonth: true, changeYear: true, dateFormat: 'dd-mm-yy'});
  if (isCms) {
    $('#'+id).datepicker('option', 'yearRange', '-01:+03');
  }
  $("#"+id+"_date").click(function() { $("#"+id).datepicker("show"); });
}

function initJQDialog(id, title, width) {
  if (!title) title = '';
  if (!width) width = 600;
  $elem = $('#'+id);
  $elem.dialog({autoOpen: false, show: "blind", hide: "blind", modal: true, width: width, title: title});
  $("#"+id+"_opener").click(function() { 
    $elem = $('#'+id);
    $elem.dialog("open"); 
    if ($("#"+id+"_crop").length > 0) {
      $("#"+id+"_crop").Jcrop({ aspectRatio: 225 / 172, onSelect: updateCoords, onChange: updateCoords });
      $('#crop_id').val('');
      $('#crop_x').val('');
      $('#crop_y').val('');
      $('#crop_w').val('');
      $('#crop_h').val('');
    }
  });
  if ($("#"+id+"_closer").length > 0) {
    $("#"+id+"_closer").click(function() { 
      $('#'+id).dialog('close');
    });
  }
}

function updateCoords(c) {
  $('#crop_x').val(c.x);
  $('#crop_y').val(c.y);
  $('#crop_w').val(c.w);
  $('#crop_h').val(c.h);
}


function setCookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}


function calculate_time_zone() {
	var rightNow = new Date();
	var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);  // jan 1st
	var june1 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0); // june 1st
	var temp = jan1.toGMTString();
	var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	temp = june1.toGMTString();
	var june2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
	var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);
	var dst;
	if (std_time_offset == daylight_time_offset) {
		dst = "0"; // daylight savings time is NOT observed
	} else {
		// positive is southern, negative is northern hemisphere
		var hemisphere = std_time_offset - daylight_time_offset;
		if (hemisphere >= 0)
			std_time_offset = daylight_time_offset;
		dst = "1"; // daylight savings time is observed
	}
	var i;

    setCookie("time_zone_dst", dst, 365, "/");
    setCookie("time_zone_offset", convert(std_time_offset), 365, "/");
}

function convert(value) {
	var hours = parseInt(value);
   	value -= parseInt(value);
	value *= 60;
	var mins = parseInt(value);
   	value -= parseInt(value);
	value *= 60;
	var secs = parseInt(value);
	var display_hours = hours;
	// handle GMT case (00:00)
	if (hours == 0) {
		display_hours = "00";
	} else if (hours > 0) {
		// add a plus sign and perhaps an extra 0
		display_hours = (hours < 10) ? "+0"+hours : "+"+hours;
	} else {
		// add an extra 0 if needed 
		display_hours = (hours > -10) ? "-0"+Math.abs(hours) : hours;
	}
	
	mins = (mins < 10) ? "0"+mins : mins;
	return display_hours+":"+mins;
}

onload = calculate_time_zone;

function toggleArrowSection($elem) {
  if ($elem.hasClass('open_arrow')) {
    $elem.removeClass('open_arrow').addClass('closed_arrow');
    $('#'+$elem.attr('id').replace('toggle_', '')).hide();
  } else {
    $elem.removeClass('closed_arrow').addClass('open_arrow');
    $('#'+$elem.attr('id').replace('toggle_', '')).show();
  }
}

