////////////////////////////////////////////////////////////////////////////////
// AJAX requests
////////////////////////////////////////////////////////////////////////////////

// Initial page load
jQuery(document).ready( function() {
  XT.defaultErrorHandler = handleErrors;
  refreshing();
  getPublishingDatesForNewspaper();
  var options = [];
  options.maxChars = BODY_MAX_CHARS;
  hookBodyCharCounter(options);
  if(hookHeadingCharCounterAtStart) {hookHeadingCharCounter();}
  if(hookImageCropperAtStart) { hookImageCropper(); }
});

// Newspaper has been selected, get publishing dates and categories for newspaper
function newspaperSelectionChanged(selectNewspaperElement, contextPath) {
  changeNewspaperLogo(selectNewspaperElement.value, contextPath);
  if(selectNewspaperElement.value == 'kmvlehti' || selectNewspaperElement.value == 'jamsanseutu' || selectNewspaperElement.value == 'jamsanseudunvekkari' || selectNewspaperElement.value == 'suurkeuruu' ) {
    openElementDisplay('spslehdet');
    closeElementDisplay('publishingDateInfo');
    openElementDisplay('publishingDateInfoSPS');
  } else {
    closeElementDisplay('spslehdet');
    closeElementDisplay('publishingDateInfoSPS');
    openElementDisplay('publishingDateInfo');
  }
  refreshing();
  clearPublishingDate();
  getPublishingDatesForNewspaper();
	getNewspaperCategories();
  getSelectDiscount();
}

// Newspaper module has been selected, get text area(s) for the module and image selection if selected module supports images
function newspaperModuleSelectionChanged() {
  refreshing();
  getNewspaperAnnouncementTexts();
  getSelectImage();
}

// Image has been selected, get image for cropping selections
function imageSelectionChanged(imageIndex) {
  refreshing();
  setSelectedImage(imageIndex);
  getSelectImage();
}

// Discount type selection has been changed, get discount selections and possibly new prices
function discountTypeSelectionChanged() {
  refreshing();
  getSelectDiscount();
  getNewspaperModules();
}

function publishingDateSelectionChanged() {
  refreshing();
  getSelectDiscount();
  getNewspaperModules();
}

function newspaperCategorySelectionChanged() {
  refreshing();
  getNewspaperModules();
   
}

// Start polling preview when newspaper announcement has been successfully added
function startPollingPreview() {
  jQuery(this).everyTime('3s', 'previewPolling', isPreviewAvailable, 0, true);
}

// When preview is available and shown to user, stop polling
function stopPollingPreview() {
  jQuery(this).stopTime('previewPolling');
}

function getNewspaperCategories() {
  XT.doSimpleAjaxSubmit('categories-for-newspaper.action', '', '');
}

function getNewspaperModules() {
  XT.doSimpleAjaxSubmit('modules-for-category.action', '', '');
}

function getPublishingDatesForNewspaper() {
  XT.doSimpleAjaxSubmit('publishing-dates-for-newspaper.action', '', '');
}

function getNewspaperAnnouncementTexts() {
  unhookHeadingCharCounter();
  unhookBodyCharCounter();
  XT.doSimpleAjaxSubmit('textareas-for-module.action', '', '');
}

function getSelectImage() {
  XT.doSimpleAjaxSubmit('select-image.action', '', '');
}

function getSelectDiscount() {
  XT.doSimpleAjaxSubmit('select-discount.action', '', '');
}

function isPreviewAvailable() {
  XT.doSimpleAjaxSubmit('is-preview-available.action', '', '');
}

////////////////////////////////////////////////////////////////////////////////
// DOM modifications
////////////////////////////////////////////////////////////////////////////////

function handleErrors() {
  stopPollingPreview();
  jQuery("#ajaxErrorMessage").show();
  scroll(0,0);
}

function hookImageCropper() {
	new Cropper.ImgWithPreview( 
        'selectedPrintImage',
		{ 
		  minWidth: 200,
		  minHeight: 111,
		  ratioDim: { x: 200, y:111 },
		  displayOnInit: true, 
		  onEndCrop: setCoordinateValues,
		  onloadCoords: {x1: $( 'x1' ).value,
		                 x2: $( 'x2' ).value,
		                 y1: $( 'y1' ).value,
		                 y2: $( 'y2' ).value}
		  } 
	);
}

function setCoordinateValues(coords) {
	jQuery("#x1").attr("value", coords.x1);
	jQuery("#x2").attr("value", coords.x2);
	jQuery("#y1").attr("value", coords.y1);
	jQuery("#y2").attr("value", coords.y2);
};

function setSelectedImage(imageIndex) {
	jQuery("#selectedImage").attr("value", imageIndex);
}

function clearPublishingDate() {
	jQuery("#publishingDate").attr("value", "");
}

function hookHeadingCharCounter() {
	jQuery('#newspaperHeadingText').addCharCounter('charsLeftHead');
}

function hookBodyCharCounter(options) {
	jQuery('#newspaperBodyText').addCharCounter('charsLeftDesc', options.maxChars);
}

function unhookHeadingCharCounter() {
	jQuery("#newspaperHeadingText").removeCharCounter();
}

function unhookBodyCharCounter() {
	jQuery("#newspaperBodyText").removeCharCounter();
}

function setPreviewSectionNumberImg(imgUrl) {
	jQuery("#previewHeader").attr("src", imgUrl);
}

function updateSelectedDay(day, millis, year, month) {

	jQuery("#publishingDate").attr("value", day);
 
	var pageLinks = document.links;
  
	for (var i=0;i<pageLinks.length;i++) {
		if (pageLinks[i].className == "calendarLink") { 
			pageLinks[i].style.border = "1px solid #ffffff"; 
			pageLinks[i].style.fontWeight = 'normal';  
		}
	}
	toggleElementDisplay('selectDateLayer');
	
	publishingDateSelectionChanged();
}

function updateBorder(whichlink) {
  whichlink.style.border = "1px solid #f00";
  whichlink.style.fontWeight = "bold";
}

function personOrCompany() {
	
  if(document.getElementById('showCompany').checked == true) { 
    openElementDisplay('companyNameAndCode');
    closeElementDisplay('personName');
    document.getElementById("firstName").value = "";
    document.getElementById("lastName").value = "";				
  } 
  else {
    closeElementDisplay('companyNameAndCode');			
	openElementDisplay('personName');
	document.getElementById("companyName").value = "";
	document.getElementById("companyCode").value = "";								
  }
}

function changeNewspaperLogo(newspaperId, contextPath) {
	jQuery('#newspaperLogo').attr("src", contextPath + "/images/announcement/" + newspaperId + ".gif");
}

function refreshing() {
	document.body.style.cursor = "wait";
	jQuery(this).stopTime('refreshing');
	jQuery(this).oneTime('800ms', 'refreshing', refreshingStopped); 
}

function refreshingStopped() {
	document.body.style.cursor = "default";
}