jQuery.ajaxSetup({'beforeSend': function (xhr) {
		xhr.setRequestHeader("Accept", "text/javascript");
	}
});



function activateLinkPanel() {
	if($("#link_panel .link").length > 0){
		
		$("#link_panel .link").hover(
		  function () {
		    $(this).addClass("link_panel_hover");
		  }, 
		  function () {
		    $(this).removeClass("link_panel_hover");
		  }
		
		);
		
		
		$("#link_panel .link").click(function () {
			var hlink = $(this).find("a").attr('href');
			document.location = hlink;
		});
		
	}
}

function setupCalendarFields() {
	$(".calendar_date").datetimeselect();
	
	$('.calendar_date.start').blur(function (event) {
		start_date = this
		fields = $(start_date).closest('.fields')
		end_date = $('.calendar_date.end', fields)
		if($(end_date).val() == ''){
			//alert("Changing");
			$(end_date).val($(start_date).val());
		}
	});

	
	
//	
//	
//	
//	if($('.calendar_date.start').length > 0 && $('.calendar_date.end').length > 0){
//		$('.calendar_date.start').blur(function (event) {
//			//alert( event.currentTarget );
//			if($('.calendar_date.end').val() == ''){
//				//alert("Changing");
//				$('.calendar_date.end').val($('.calendar_date.start').val());
//			}
//		});
//	}
}

function setupEventForm() {
	if ($('.ignore_end_date').length > 0) {	
		$('.ignore_end_date').click(function () {
			fields = $(this).closest('.fields')
			$('.end_date', fields).toggle('fast');
		});
	}
	
	if ($('.event_location_select').length > 0) {
		$('.event_location_select').click(function () {
			$('.in_store').toggle("fast");
			$('.event_address').toggle("fast");
		});
	}
}

function scroll_to(id){
     	$('html,body').animate({scrollTop: $(id).offset().top},'slow');
}


function hideBilling() {
	if ($('.hide_billing').length > 0) {
		
		$('.hide_billing').click(function () {
			$('.billing_details').toggle("fast");
		});
	}
}

function get_in_store_availability() {
	if ($('div.in_store').length > 0) {
		$('div.in_store').hide();
		$.post('/products/get_in_store_availability.js', { id: $('#pid').val() }, null, "script");
	}
}


function prevent_auto_complete() {
	//this is an attempt to prevent browsers from populating password fields in the edit forms
	if ($("form").length > 0) {
		$("form").attr("autocomplete", "off");
		$("input").attr("autocomplete", "off");
	}
}
function toggle_feature_controls() {
	if ($('input.is_banner').length > 0) {
		//setup toggle on checkbox
		$('input.is_banner').click(function () {
			$('div.text_content').toggle();
		});
	}
}

function show_info() {
	if ($('.show_info').length > 0) {
		$('.show_info').click(function () {
			$("div.info").toggle();
			return false;
		});
	}
}

function toggle_address() {
	if ($('.show_address').length > 0) {
		$('.show_address').toggle(function () {
			$(".rest_of_address, this.parent").show("fast");
			$(this).html("hide");
			return false;
		}, function () {
			$(".rest_of_address, this.parent").hide("fast");
			$(this).html("show");
			return false;
		});
	}
}

function remove_fields(link) {
	$(link).prev("input[type=hidden]").val("1");
	$(link).closest(".fields").hide();
}

function add_fields(link, association, content) {
	var new_id = new Date().getTime();
	var regexp = new RegExp("new_" + association, "g");
	$(link).parent().before(content.replace(regexp, new_id));
	
	//trigger the javascripts/dynamic_specific_placement_locations.js.erb to be run
	if($('select.placement_location_id').length > 0) {
		locationSelected($('select.placement_location_id').last());
	}
	
	if($('select.collection_type_id').length > 0) {
		typeSelected($('select.collection_type_id').last());
	}
	
	if ($('.ignore_end_date').length > 0) {	
		$('.ignore_end_date').last().click(function () {
			fields = $(this).closest('.fields')
			$('.end_date', fields).toggle('fast');
		});
	}
	
	if($('.calendar_date.start').length > 0) {
		$('.calendar_date.start').last().blur(function (event) {
			start_date = this
			fields = $(start_date).closest('.fields')
			end_date = $('.calendar_date.end', fields)
			if($(end_date).val() == ''){
				//alert("Changing");
				$(end_date).val($(start_date).val());
			}
		});
	}
	
	last_fields = $('.fields').last();
	$(".calendar_date", last_fields).datetimeselect();
	
	
	
	
	
	return false;
}


function buildBookShelves() {
	//check if we have any bookshelves to build
	if ($(".bookshelf").length > 0) {
	
		// select .bookshelf and make it scrollable. use navigator plugin

		$(".bookshelf").scrollable({
			size: 1,
			clickable: false,
			items: ".bookshelf_shelves"
		}).navigator({		
			// select .bookshelf_tabs to be used as navigator
			navi: ".bookshelf_tabs",
			
			// select A tags inside the navigator to work as items (not direct children)
			naviItem: "a",
			
			// assign "current" class name for the active A tag inside navigator
			activeClass: "current"
		});		
	}
		
		
	if ($(".bookshelf_shelf_contents").length > 0) {

		$(".bookshelf_shelf_contents").scrollable({
			size: 6,
			clickable: true,
			nextPage: '.next_page.right',
			prevPage: '.next_page.left'
		});	
		
		//remove href attribute from shelf next/prev buttons
		$(".next_page").removeAttr('href'); 		
	}	
}

function initCartMenu() {
	menu = $('#cart_menu_list');
	menu.hide();
	
	
	$('#cart_float').bind("hover", { speed: 100, delay: 200 }, function () {	
		$('#cart_float #btn_cart a').addClass("open");
		$('#cart_menu_list').stop(true, true).show(1);
	});
	
	/*
	$('#cart_float').mouseenter(function() {
			$('#cart_menu_list').stop(true,true).slideDown(300);		 
	});
		*/
	$('#cart_float').mouseleave(function () {
		$('#cart_menu_list').stop(true, true).delay(3000).hide(1, function () {
			$('#cart_float #btn_cart a').removeClass("open");
		});	
	});
	
	$(document).click(function () {
		//if you click outside the menu, close it
		$('#cart_menu_list').stop(true, true).hide(1, function () {
			$('#cart_float #btn_cart a').removeClass("open");
		});
	});
	
	$('#cart_float').click(function (event) {
		//prevent clicking in the menu closing it
		event.stopPropagation();
	});
	
	
	//add mouse click event to list items and change cursor to pointer - we want to be able to click the whole list item to go to the product
	$('#cart_menu_list li').each(function () {
		$(this).click(function () {
			window.location = $('a', this).attr('href');
		});
	});
	
}

$(document).ready(function () {
	activateLinkPanel();
	$.preloadCssImages();
	$(".rounded").corners();
	buildBookShelves();
	initCartMenu();
	show_info();
	toggle_feature_controls();
	//toggle_address();
	prevent_auto_complete();
	//get_in_store_availability(); //shelved - done at product request
	hideBilling();
	if ($("label.spesh").length > 0) {
		$("label.spesh").inFieldLabels();
	}
	
	if ($(".existing_user_switch").length > 0) {
		$(".existing_user_switch").click(function () {
			$("#non_existing_panel").toggle("fast");
			$("#existing_panel").toggle("fast");
		});
	}
	
	$("#cart_delivery_country_code").change(function () {
		$('.ajax_shipping_total').hide();
		$('.loader').show();
		this.form.submit();
	});
	
	
	if ($('a.scroll_to').length > 0) {
		$('a.scroll_to').click(function () {
			scroll_to($(this).attr('href'));
			return false;
		});
	}
	
	Shadowbox.init({
    // skip the automatic setup again, we do this later manually
    	skipSetup: true
	});


	
	Shadowbox.setup(".berkelouw_history_gallery", {
        gallery: "Berkelouw History"
    });
	
	
	$('.vform').ketchup({
		validationAttribute: 'rel',
		errorContainer: $('<div>', {
			'class': 'ketchup-error-container-alt',
			html: '<ol></ol>'
		}),
		
		initialPositionContainer: function(errorContainer, field) {
			//errorContainer = the error-container with all childs
			//field = the field that needs to get validated
			
		},
		
		positionContainer: function(errorContainer, field) {
			//$(field).attr("style","border:red 1px solid;background-image:url(../images/validation_warning.gif);background-position:right;background-repeat:no-repeat;");
			//$(field).attr("style","border:red 1px solid;");
		},
		
		showContainer: function(errorContainer) {
			errorContainer.slideDown('fast');
			$(errorContainer).prev('.input').attr("style","border:red 1px solid;background-color:#FFFFCC");
		},
		
		hideContainer: function(errorContainer) {
			errorContainer.slideUp('fast');
			$(errorContainer).prev('.input').attr("style","border: #999 1px solid;background-color:#fff");
		}		
	});
	
	
	//setupCalendarFields();
	

	
   
	setupEventForm();
	
	
	
	//replace missing images
	//replaced with missingImage function below
	// $('img').error(function() { 
	// 		$(this).attr({src: '/images/no_cover.jpg', alt: 'Image is not available'});
	// 	});

});

function missingImage(i) {
	i.src = "/images/no_cover.jpg";
	i.alt = "Image is not available";
	// disable onerror to prevent endless loop
	source.onerror = "";
	return true;
}

function checkAndDisableWeek()	{
	if($('#event_event_recurring_attributes_on').length == 0)	{
		// element not available with the id event_event_recurring_attributes_on
	}
	else{
		var selectedValue = $('#event_event_recurring_attributes_on').val();
		if(selectedValue.length <= 2 || selectedValue == "sunday"  || selectedValue == "monday" || selectedValue == "tuesday" || selectedValue == "wednesday" || selectedValue == "thursday" || selectedValue == "friday" || selectedValue == "saturday")	{
			$('#event_event_recurring_attributes_weekday').attr("disabled", "disabled");
		}
		else	{
			$('#event_event_recurring_attributes_weekday').attr("disabled", "");
		}
	}		
	
}



// methods used in the page, link product to events/posts/collections


function removeProductFromList(productIsbn)	{
	var divId = 'product_' + productIsbn;
	$('#'+divId).remove();
	removeIsbnFromTextArea(productIsbn);
	return false;
}

function removeIsbnFromTextArea(isbn)	{
	var updatedIsbnValues = new Array(), arrayIndex = 0;
	$.each($('#isbn').val().split(','), function(index, value){
		if(value == isbn){
		}
		else	{
			updatedIsbnValues[arrayIndex] = value;
			arrayIndex += 1;
		}
	});
	$('#isbn').val(updatedIsbnValues.join(','));
}

function hideSpinner()	{
	$('#spinner').toggle();
}


function postEventIsbnForm(isbnValues, eventId)	{
	$('#spinner').toggle();
	if(eventId == 'new') {
		jQuery.ajax({data:'isbn=' + isbnValues, dataType:'script', type:'post', url:'/hq/events/display_products'});	
  }
  else {
	  jQuery.ajax({data:'isbn=' + isbnValues + '&event_id=' + eventId, dataType:'script', type:'post', url:'/hq/events/display_products'});
	}
 }

function postCollectionIsbnForm(isbnValues, collectionId)	{
	$('#spinner').toggle();
	if(collectionId == 'new')	{
		jQuery.ajax({data:'isbn=' + isbnValues, dataType:'script', type:'post', url:'/hq/collections/display_products'});	
	}
	else	{		
		jQuery.ajax({data:'isbn=' + isbnValues + '&collection_id=' + collectionId, dataType:'script', type:'post', url:'/hq/collections/display_products'});	
	}
}

function postIsbnForm(isbnValues, postId)	{
	$('#spinner').toggle();
	if(postId == 'new')	{
		jQuery.ajax({data:'isbn=' + isbnValues, dataType:'script', type:'post', url:'/hq/posts/display_products'});	
	}
	else	{		
		jQuery.ajax({data:'isbn=' + isbnValues + '&post_id=' + postId, dataType:'script', type:'post', url:'/hq/posts/display_products'});	
	}
}

//~ jQuery.ajax({data:'authenticity_token=' + encodeURIComponent('6HBaeU6PFyeepJImvC9m6MhdCyixPXS+6pe3tBh1ZaM='), dataType:'script', type:'post', url:'/hq/events/display_products'});
//~ $('#spinner').toggle();

function showElement(elementId)	{
	$('#'+elementId).toggle();
}

function removeResultFromList(productIsbn)	{
	var divId = 'product_' + productIsbn;
	$('#'+divId).remove();
	removeIsbnFromTextBox(productIsbn);
	return false;
}

function removeIsbnFromTextBox(isbn)	{
	var updatedIsbnValues = new Array(), arrayIndex = 0;
	$.each($('#q').val().split(','), function(index, value){
		if(value == isbn){
		}
		else	{
			updatedIsbnValues[arrayIndex] = value;
			arrayIndex += 1;
		}
	});
	if(updatedIsbnValues.length == 0)	{
		// toggleElement('add_product_button');
	}
	$('#q').val(updatedIsbnValues.join(','));
}


function toggleElement(elementId)	{
	$('#' + elementId).toggle();
}

function toggle(elementID){
var target1 = document.getElementById(elementID)
if (target1.style.display == 'none') {
target1.style.display = 'block'
} else {
target1.style.display = 'none'
}
} 

 function toggleStatus() {
		if ($('.hide_billing').is(':checked')){
			//~ // alert('checked');
			
			//~ //alert($('.billing_details').children().find('input')[0]);
			$('.billing_details :input').attr("rel","");
		}else{
			
			//~ // alert('unchecked');
			//~ //alert($('.billing_details').children().find('input')[0]);
			$('.billing_details :input').attr("rel","validate(required)");
			if(ERRORCONTAINERJS && ERRORCONTAINERJS.length > 0)
			{
				for(i=0;i<ERRORCONTAINERJS.length;i++)
				{
					ALLOPTIONS.hideContainer(ERRORCONTAINERJS[i]);
				}
				ERRORCONTAINERJS = []
				ALLOPTIONS = ""
			}
		
		
			
		}
}

function openwindow(id)
{
  window.open("/hq/orders/"+id+"/download_partial_order_receipt","mywindow","menubar=1,resizable=1,width=650,height=450");
} 

$(document).ready(function() { 
		// bind 'myForm' and provide a simple callback function 
		if($('.ajax').length > 0)	{
			$('.ajax').ajaxForm({
				dataType: 'script'
			}); 
		}
}); 

var timeOut;
var _pdfUpload = {	
	running: true,
	defaultTiming: 2000
};

function startDisplayProcess(status)	{	
	updateProgressStatus(status);
	timeOut = setTimeout("changeContent()", 2000);
	//~ changeContent();
}

function changeContent()	{	
	if(_pdfUpload.running)	{
		jQuery.ajax({data:'data_id=' + _pdfUpload.dataId, dataType:'script', type:'post', url:'/hq/products/update_ui'});			
		timeOut = setTimeout("changeContent()", 4000);
	}
	else	{
		clearTimeout(timeOut);
	}
}

function updateProgressStatus(content)	{
	$('#uiDisplay').html(content);
}

function getCookieValueFor(cookieKey)	{
	var cont = document.cookie;
	var arr = cont.split('=');
	for(var i=0; i<arr.length;i++)    {
		if(arr[i]==cookieKey)	{
			return (arr[i+1].replace(/\+/g,' '));
		}    
	}
}

function setStatusId(record_id)	{
	_pdfUpload.dataId = record_id;	
}

function stopProcess()	{
	_pdfUpload.running = false;
}

function toggleSpinner(elemId)	{
	$('#'+elemId).toggle();
}

function setToVisible(elemId)	{
	$('#'+elemId)[0].style.display = 'inline';
}

function searchProductGenre(genreVal, productId){
	jQuery.ajax({data: 'genre_code=' + genreVal + '&product_id=' + productId, dataType:'script', type:'post', url:'/hq/products/display_genres_list'});
}

function addGenreProduct(genreVal,Id, productId){
		jQuery.ajax({data: 'genre_code=' + genreVal  + '&hide_id=' + Id + '&product_id=' + productId, dataType:'script', type:'post', url:'/hq/products/add_genre'});
		$('#'+Id).fadeOut(1000, function () {
		 $('#'+Id).remove();
		});	
	}
	
function newGenreProduct(genreVal){
	jQuery.ajax({data: 'genre_code=' + genreVal, dataType:'script', type:'post', url:'/hq/products/list_genres'});
}

function addGenre(genreVal,itemId){
   if (document.getElementById('genre_values').value == "" || document.getElementById('genre_values').value == null){
		document.getElementById('genre_values').value = genreVal
		}
	 else{
		document.getElementById('genre_values').value = document.getElementById('genre_values').value + "," + genreVal
		}	
		$('#'+itemId).fadeOut(1000, function () {
			$('#'+itemId).remove();
		});
		jQuery.ajax({data: 'genre_code=' + document.getElementById('genre_values').value + '&item_id=' + itemId, dataType:'script', type:'post', url:'/hq/products/add_genre_to_product'});
	}
	
function removeGenre(genreId,genreCode){
		var str = document.getElementById('genre_values').value
		var arr = str.split(",");
		arr = jQuery.grep(arr, function(value) {
			return value != genreCode;
		});
		document.getElementById('genre_values').value = arr.toString()
		$('#'+genreId).remove();
	}

	function searchGenresInGenericProduct(genreVal){
		jQuery.ajax({data: 'genre_code=' + genreVal, dataType:'script', type:'post', url:'/hq/generic_products/list_genres'});
	}
	
	function addGenreToGenericProduct(genreVal,itemId){
		if (document.getElementById('genre_values').value == "" || document.getElementById('genre_values').value == null){
			document.getElementById('genre_values').value = genreVal
		}
	  else{
		 document.getElementById('genre_values').value = document.getElementById('genre_values').value + "," + genreVal
		}	
		$('#'+itemId).fadeOut(1000, function () {
			$('#'+itemId).remove();
		});
		jQuery.ajax({data: 'genre_code=' + document.getElementById('genre_values').value + '&item_id=' + itemId, dataType:'script', type:'post', url:'/hq/generic_products/add_genre_to_product'});
	}
	
	function searchGenericProductGenre(genreVal, productId){
	  jQuery.ajax({data: 'genre_code=' + genreVal + '&product_id=' + productId, dataType:'script', type:'post', url:'/hq/generic_products/display_genres_list'});	
	}
	
	function addGenreInGenericProduct(genreVal,Id, productId){
		jQuery.ajax({data: 'genre_code=' + genreVal  + '&hide_id=' + Id + '&product_id=' + productId, dataType:'script', type:'post', url:'/hq/generic_products/add_genre'});
		$('#'+Id).fadeOut(1000, function () {
			$('#'+Id).remove();
		});	
	}
	
	function highlight_item(val){
		$('#'+val+' ul').children().last().effect('highlight', {color:"yellow"}, 3000)
 }
