// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function toggleMessages() {
	messages = $("#messages_container");
	tabs = $("#left_nav_bottom_tabs");
	if (messages.length < 1 || tabs.length < 1)
		return;
	tabs.toggle();
	messages.toggle();
}

function toggleStats() {
	stats = $("#stats_container");
	tabs = $("#left_nav_bottom_tabs");
	if (stats.length < 1 || tabs.length < 1)
		return;
	tabs.toggle();
	stats.toggle();
}

function hideOverlay() {
	$('#fancy_outer').hide();
	$('#fancy_overlay').hide();
}

function manualPictureCode(photo_id, post_path, redirect_path) {
	jPrompt(
		'Enter code:',
		'000-000-000',
		'Manually Parse Picture Code',
		function(res) {
			if (!res)
				return;
			$.post(post_path, {'id': photo_id, 't':	res }, function (data) { 
				if (data == 'Success') {
          window.top.location.reload(true);
        }
			  else
					jAlert("The code that you entered was invalid.  Please verify that you are using a valid code.", "Error");
			});
		}
	);
}

function removePictureCode(taqq, post_path, redirect_path) {
  $.post(post_path, {'t':	taqq }, function (data) { 
    if (data == 'Success') {
      window.top.location.reload(true);
    }
    else
      jAlert(data);
  });
}

function ajaxSpinnerHtml() {
  return '<img class="spinner" alt="loading..." src="/images/ajax-loader.gif">';
}

function submitCartPurchase() {
  $('.cart-button').parent().html(ajaxSpinnerHtml());
  $('.cart-small-button').parent().html(ajaxSpinnerHtml());
  $('#cc_form').submit();
}
function toggle_more_info() {
  $('#more_info').toggle();
  $('#plus_info').toggle();
  $('#minus_info').toggle();
}

function registerTranslatableItems() {
  $('.translated').each(function() {
    $(this).hover(function() {
      $('#translation_key').html($(this).next().html());
    }, function() {
      $('#translation_key').html('hover over a word to see key');
    })
  });  
}

//$(document).ready(function() {
  //registerTranslatableItems();
//})
function job_setup_segment_onchange() {
  if ($('#job_segment').val() == 'school')
    $('#job_privacy_options').hide();
  else
    $('#job_privacy_options').show();
}
function job_setup_privacy_onchange() {
  //Show the password stuff if the password setting (id == 3) is checked
  if ($('#job_privacy_setting_3').attr('checked'))
    $('#job_password_setup').show();
  else
    $('#job_password_setup').hide();
}
function select_photo_list(list_name) {
  if (list_name == 'your') {
    $('#your_photo_list').show();
    $('#group_photo_list').hide();
    $('#your_photo_link').addClass('photo-list-link-active');
    $('#group_photo_link').removeClass('photo-list-link-active');
  }
  else {
    $('#your_photo_list').hide();
    $('#group_photo_list').show();
    $('#your_photo_link').removeClass('photo-list-link-active');
    $('#group_photo_link').addClass('photo-list-link-active');
  }
}

rotate = function() {
  var rotation =  parseInt($("#rotation").html());
  rotation = ((rotation + 90) % 360)
  $("#rotation").html(rotation.toString()+"&deg;");
  
  $("#edit_photo").rotateRight();
  
	$("#apply_rotation").show();
}

applyRotation = function(pid,jid) {   
  $.post('/job_photos/apply_batch_rotation', {
    photo_ids: pid,
    job_id: jid,
    r: parseInt($("#rotation").html())
  }, function(resp) {
    jAlert(resp['msg'], 'Photos rotating', function() {
      window.top.location = resp['redirect'];
    });
  }, 'json');    
}

cancelRotation = function() {
  var rotation =  parseInt($("#rotation").html());

  while(rotation != 0) {
    rotation = ((rotation + 90) % 360)
    $("#rotation").html(rotation.toString()+"&deg;");
    $("#edit_photo").rotateRight();
  }
  
  $("#apply_rotation").hide();
}

function bibNumberOnKeyUp(e) {
	if (e.which == 13) { //enter
		e.stopPropagation()
		$('#next_link').click();		
	}
}
function saveBibNumber(path, closeAfterSaving, next_path) {
	$.post(
		path, 
		{ _method: 'put', 'photo[custom_identifier_list]': $('#photo_custom_identifier_list').val() },
		function(data) {
			if (closeAfterSaving) {
				window.top.hideOverlay();
			}
			else {
				$('body').load(next_path);
			}
		}
	);

}

function showTabs(tabName, tabGroup) {
	$("." + tabGroup.replace(/_/g,'-') + "-tab").each(function() { $(this).removeClass('active'); })
	$("." + tabGroup.replace(/_/g,'-') + "-tab").each(function() { $(this).addClass('inactive'); })
	$("." + tabGroup.replace(/_/g,'-') + "-content").each(function() { $(this).hide(); })
	
	$("#" + tabGroup.replace(/-/g,'_') + "_" + tabName + "_tab").addClass('active');
	$("#" + tabGroup.replace(/-/g,'_') + "_" + tabName + "_tab").removeClass('inactive');
	$("#" + tabGroup.replace(/-/g,'_') + "_" + tabName + "_content").show();
}

function showOrderDetails(order_id) {
  button = $('#detail_button_' + order_id).parent();
  button.html('<img src="/images/ajax-loader.gif"/>');
  $.ajax({
    type: "GET",
    url: '/photographer/orders/' + order_id + '/listing_detail', 
    success: function(html) {
      $('#order_' + order_id).after(html);
      button.hide();
			$('#order_' + order_id).css('border-bottom','none');
    },
    error: function() {
      button.html('Request Failed');
    }
  });
}

function disableEnterSubmit (event) {
	if (event.keyCode == '13') {
		event.preventDefault();
		return false;
	}
}
function orderFormSelectPhoto(image_path, image_id, raw_url, preview_url) {
  $('#selected_photo').html(image_path);
  $('#photo_id').val(image_id);
	fullSizeUrl = $('#photo_id').attr("full_size_url", raw_url);
	fullSizeUrl = $('#photo_id').attr("preview_url", preview_url);
	orderFormZoomOutPhoto();
}
function orderFormZoomInPhoto() {
	$('#zoom_in').css('background-position','0 0');
	$('#zoom_out').css('background-position','0px -30px');
	fullSizeUrl = $('#photo_id').attr("full_size_url");
	$('#selected_photo img').attr("src",fullSizeUrl);
	$('#selected_photo img').css('max-height','none');
	$('#selected_photo img').css('max-width','none');
}
function orderFormZoomOutPhoto() {
	$('#zoom_out').css('background-position','0 0');
	$('#zoom_in').css('background-position','0px -30px');
	previewUrl = $('#photo_id').attr('preview_url');
	$('#selected_photo img').attr('src',previewUrl);
	$('#selected_photo img').css('max-height','');
	$('#selected_photo img').css('max-width','');
}
function validateNewOrder() {
  errors = [];
  fields = ['first_name',
    'last_name',
    'address_line_1',
    'city',
    'zip',
    'country'];
  errors.push(validateAddress('billing')); //validate billing info
  errors.push(validateAddress('shipping')); //validate shipping info
  if($('#email').val() == "") //validate e-mail address
    errors.push('email address');
  else {
    var email_regex = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if(email_regex.test($('#email').val()) == false)
      errors.push(INVALID_EMAIL);
  }
  if ($("input[name='card_number']").val().length != 0 && $("input[name='payment_type']:checked").val() == 'credit_card') // validate CVV
    errors.push(validateCVV());
  plpFound = false; // validate that there is a non-zero quantity for at least one price list purchasable
  $.each($('#item_selection input'), function(index,value) {
    if ($(value).val() != 0)
      plpFound = true;
  });
  if (plpFound == false)
    errors.push(NO_PLP);
  errors = $.map(errors, function(value){return value}); // flattens array
  if (errors.length == 0) {
    $('#order_form_errors').hide();
    return true;
  }
  else {
    $('#order_form_errors').html(ORDER_FIELDS_MISSING+' '+errors.join(', ')+'.');
    $('#order_form_errors').show();
    $('#order_form_errors').focus();
    return false;
  }
}
function handleShipping() {
  $.ajax({
    url: '/cart/choose_shipping_option',
    type: "POST",
    data: ({
      cart_id: $('#cart_id').val(), 
      offline: '1',
      address_line_1: $('#order_shipping_address_line_1').val(),
      address_line_2: $('#order_shipping_address_line_2').val(),
      city: $('#order_shipping_city').val(),
      state: $('#order_shipping_state').val(),
      zip: $('#order_shipping_zip').val(),
      country: $('#order_shipping_country').val()
    }),
    success: function(html) {
      $('#cart_summary').after(html); 
      $('#shipping_required').val('0');
    },
    error: function(html) {
      jAlert('There was an error processing shipping information.  Please verify that the shipping address you entered was valid.');
    }
  });
  return true;
}
function submitNewOrder() {
  is_valid = validateNewOrder();
  if (!is_valid) {
    return false;
  }
  if ($('#shipping_required').val() == '1') {
    handleShipping();
    return false;
  }
  data = $('#new_order').serialize();
  $.post('/photographer/orders/add_order', data, function(res) {
    if (res['status'] == 'success') {
      alert(res['message']);
      document.location = '/photographer/orders';
    }
    else {
      $('#order_form_errors').html(res['message']);
      $('#order_form_errors').show();
    }
    
  }, 'json');

  return false;
}
function validateAddress(addressArea) {
	errorFields = [];
	$.each(fields, function(index) {
		if ($('#order_'+addressArea+'_'+fields[index]).val() == "")
			errorFields.push($("label[for='order_" +addressArea+'_'+fields[index]+ "']").html());
	});
	return $.map(errorFields, function(errorName) {
		return addressArea+' '+errorName.toLowerCase();
	});
}
function copyBillingToShipping() {
	if ($('input[name=same_address]').attr('checked') == true){
		countrySelect($('#order_billing_country')); // must call this before billingSameAsShippin so state fields match.
		$.each($('.address-element'), function(index, value) {billingSameAsShipping(value);} );
	}
}
function billingSameAsShipping(elem) {
	formElem = $(elem);
	if ($('input[name=same_address]').attr('checked') == true) {
		if (formElem.attr('id').search('billing') != -1) {
			partnerElem = $('#' + formElem.attr('id').replace('billing','shipping'));
		}
		else {
			partnerElem = $('#' + formElem.attr('id').replace('shipping','billing'));
		}
		partnerElem.val(formElem.val());
		if (partnerElem.attr('id').search('country') != -1) {
			countrySelect(partnerElem);
		}
	}
}
function countrySelect(elem) {
	var country = $(elem);

	hideShowStates(country);

	if ($('input[name=same_address]').attr('checked') == true) {
		if (country.attr('id').search('billing') != -1) {
			var partnerCountry = $('#' + country.attr('id').replace('billing','shipping'));
		}
		else {
			var partnerCountry = $('#' + country.attr('id').replace('shipping','billing'));
		}

		partnerCountry.val(country.val());
		hideShowStates(partnerCountry);
	}
}
function hideShowStates(elem) {
	country = $(elem);
	name = country.attr('name').replace('country','state');
	id = country.attr('id').replace('country','state');

	if (country.val() == 'USA' || country.val() == 'CA') {
		formElemOn = $('.' + id  + ' select');
		formElemOff = $('.' + id  + ' input');
	}
	else {
		formElemOn = $('.' + id  + ' input');
		formElemOff = $('.' + id  + ' select');
	}

	formElemOn.show();
	formElemOn.attr('name',name);
	formElemOn.attr('id',id);
	formElemOn.attr('class','address-element');

	formElemOff.hide();
	formElemOff.attr('name','');
	formElemOff.attr('id','');
	formElemOff.attr('class','');
}
function selectPaymentType() {
	$('.order-form-check').hide();
	$('.order-form-credit-card').hide();
	if ($("input[name='payment_type']:checked").val() == "credit_card")
		$('.order-form-credit-card').show();
	if ($("input[name='payment_type']:checked").val() == "check")
		$('.order-form-check').show();
}
function validateCVV() {
	if (($("#card_type_").val() != "american_express" && $("input[name='card_cvv']").val().length == 3) ||
		 ($("#card_type_").val() == "american_express" && $("input[name='card_cvv']").val().length == 4))
		return [];
	else
		if ($("#card_type_").val() != "american_express")
			return [PLEASE_ENTER_CVV];
		else
			return [PLEASE_ENTER_AMEX_CVV];
}

g_highestAddCartPurchasableSequence = 0;

function addCartPurchasable(target) {
  target = $(target);
	$('#products_to_crop').hide();

  // Strip non-positive integers
  value = target.val().replace(/\D/g, '');
  if (value == '') value = 0;
  value = parseInt(value, 10);
  target.val(value);

  $('#cart_summary').html('<img src="/images/ajax-loader-green-gray.gif"/>');
  $.ajax({
    url: '/cart/add_to_cart',
    type: "POST",
		dataType: 'json',
    data: ({
      job_id: $('#job_id').val(),
      subject_id: $('#subject_id').val(), 
      cart_id: $('#cart_id').val(), 
      purchasable_id: target.attr('id').split('_')[2],
      photo_id: $('#photo_id').val(),
      offline: '1',
      quantity: target.val()}),
    success: function(resp) {
			sequence = parseInt(resp['sequence'] , 10);
			if (sequence > g_highestAddCartPurchasableSequence){
				g_highestAddCartPurchasableSequence = sequence;
				$('#cart_summary').html(resp['content']); 
			}
    },
    error: function(html) {
      $('#cart_summary').html(html);
    }
  }, 'json');
}
function plus_minus_purchasable(elem, plusMinus) {
	target = $(elem).siblings('input');
	value = parseInt(target.val(),10); 
	if (value == '')
		value = 0;

	if (plusMinus == 'plus')
		newVal = value + 1;
	if (plusMinus == 'minus') {
		newVal = value - 1;
		if (newVal < 0)
			newVal = 0;
	}

	target.val(newVal);
	addCartPurchasable(target);
}
function displayForCrop(cartID, cartPurchasableID) {
	$('.cart-purchasable').css('border', 'solid 1px #777777');
	var cpID = cartPurchasableID;
	$('#products_to_crop').html('<img src="/images/ajax-loader.gif"/>');
	$('#products_to_crop').load("/photographer/orders/cart_purchasables_to_crop?cart_id="+cartID+"&cp_id="+cpID);
	var backgroundColor = $('#cp_' + cpID).css('background-color');
	$('#products_to_crop').css('background-color', backgroundColor);
	$('#products_to_crop').show();
	$('#cp_' + cpID).css('border-right', 'none');
	$('#cp_' + cpID).css('border-left', 'none');
	$('#cp_' + cpID).children('#item-crop-button').children().css('background-position',"0px -30px");
}

function exportOrderCSV() {
  $('#csv_export').val('1');
  $('#order_filter_form').submit();
  
}