$(function() {

	$("table.sq_table").treeTable({
		initialState : 'collapsed'
	});

	// expand tree to show pages awaiting approval and/or last updated record
	$('table.treeTable tr').each(function() {
		if ($(this).hasClass('approval_requested') || $(this).hasClass('lastUsed')) {
			$(this).reveal();
		}
	});

	$('#social-media-feed').socialFeed({
	    limit : 8,
	    updatePath : '/helpers/updateSocialFeed.php',
	    twitterIcon : '/images/icon_sm-twitter.png',
	    facebookIcon : '/images/icon_sm-facebook.png',
	    bloggerIcon : '/images/icon_sm-blogger.png',
	    updateInterval : 30
	});

	$('.foil').each(function() {

		$(this).children().css({
		    'position' : 'relative',
		    'z-index' : '40'
		});

		/* ie6 fix */
		var height = $(this).height();
		var width = $(this).width();

		$(this).css('width', width);
		$(this).css('height', height);
		width += 100;
		height += 100;
		var height = $(this).outerHeight();
		$(this).append('<div class="foilBackground"></div>');
		$(this).find('.foilBackground').css({
		    'width' : width + 'px',
		    'height' : height + 'px'
		});

	});

	// / Collecting Addresses in cart section
	if ($('div.#div_different_shipping input.checkbox').attr('checked')) {
		$('div#shippingAddress').show();

	}

	$('div.#div_different_shipping input.checkbox').change(function() {
		if ($(this).attr('checked')) {
			$('div#shippingAddress').fadeIn();
		} else {
			$('div#shippingAddress').fadeOut();
		}
	});

	// ///////////

	// add default text to input boxes
	$('.swapValue').each(function(n) {
		if ($(this).val().length == 0) {
			$(this).val($(this).attr('title'));
			$(this).addClass('ghostInput');
		}
		$(this).bind('focus', function() {
			if ($(this).val() == $(this).attr('title')) {
				$(this).val('');
				$(this).removeClass('ghostInput');
			} else {
				$(this).select();
				$(this).removeClass('ghostInput');
			}
		});
		$(this).bind('blur', function() {
			if ($(this).val().length == 0) {
				$(this).val($(this).attr('title'));
				$(this).addClass('ghostInput');
			} else {
				$(this).removeClass('ghostInput');
			}
		});
	});

	$('form').bind('submit', function() {
		$('.swapValue').each(function() {
			if ($(this).val() == $(this).attr('title')) {
				$(this).val('');
			}
		});
	});

	// make sure links are using target="_blank" as well as rel="external"
	$('a[rel=external]').each(function(n) {
		$(this).attr('target', '_blank');
		$(this).attr('title', 'Open ' + $(this).attr('href') + ' in a new window');
	});

	// lightbox
	$("a.fancyBox").colorbox({
	    photo : true,
	    opacity : 0.65,
	    scalePhotos : true,
	    maxWidth : '75%',
	    maxHeight : '75%'
	});

	if ($.browser.msie && $.browser.version == "6.0") {
		// http://www.youtube.com/watch?v=MiCnB35k3Uk
		var url;
		$('a.videoBox').each(function() {
			url = $(this).attr('href');

			url = url.replace(".com/v/", ".com/watch?v=");
			$(this).attr('href', url);
		});
	} else {
		$('a.videoBox').colorbox({
		    iframe : true,
		    innerWidth : 640,
		    innerHeight : 390
		});
	}

	$('ul#galleryList li a').colorbox({
		scrolling : false
	});

	// ui calendar
	$('input.datePicker').datepicker({
	    changeMonth : true,
	    changeYear : true,
	    dateFormat : 'dd/mm/yy',
	    showOn : 'button',
	    buttonImage : '/images/btn_calendar.gif',
	    buttonImageOnly : true,
	    autoSize : true,
	    buttonText : 'Select a date from a calendar',
	    yearRange : 'c-90:c+10'
	});

	// cms image rollovers

	$('div#cmsImages ul li a').each(function(n) {
		var image = $(this).attr('href');
		var src = '/thumb/phpThumb.php?src=' + image + '&w=455&h=374&zc=1';
		var $this = $(this);

		if (n > 0) {
			// preload large image
			$(this).children('img').hide();
			$('<img />').attr('src', src).load(function() {
				// console.log('pre-loaded: ' + $(this).attr('src'));
				$this.children('img').fadeIn();
			});
		}

		// add click event
		$(this).bind('click mouseover', function(e) {
			e.preventDefault();
			$('a#imageTarget').attr('href', image);
			$('a#imageTarget img').attr('src', src);
		});

	});

	// gallery mouse over
	$('ul#galleryList li a').live('mouseenter mouseleave', function(e) {
		if (e.type == 'mouseover') {
			var top = 185 - $(this).children('div').outerHeight();
			$(this).children('div').animate({
				'top' : top
			}, {
			    'duration' : 500,
			    'easing' : 'easeOutQuad',
			    'queue' : false
			});
		} else {
			$(this).children('div').animate({
				'top' : '169px'
			}, {
			    'duration' : 500,
			    'easing' : 'easeOutQuad',
			    'queue' : false
			});
		}
	});

	$('#mapExpander').bind('click', function() {
		var animateTo = ($('#GMap').parent().hasClass('expanded')) ? '200px' : '558px';
		$('#GMap').parent().animate({
		    'width' : animateTo,
		    'height' : animateTo
		}, {
		    'duration' : 500,
		    'step' : function() {
			    google.maps.event.trigger(myMap, 'resize');
			    myMap.setZoom(myMap.getZoom());
		    },
		    'complete' : function() {
			    myMap.setZoom(myMap.getZoom());
			    $(this).toggleClass('expanded');
			    myMap.panTo(markers[0].getPosition());
		    }
		});

	});

	$('input.removeFromCartButton').bind('click', function(e) {
		e.preventDefault();
		$(e.target).closest('tr').find('input[type=text]').val('0');
		$(this).parents('form:first').submit();

	});

	/**
	 * inline edits
	 */

	/**
	 * inline edits disabled due to IE6 transparency fixes conflict !!!
	 * 
	 */
	/*
	 * $('div.editableMCE,div.editableText').live( 'mouseover mouseout',
	 * function(e) { var $button = $(this).find('a.editContentButton'); if (
	 * e.type == 'mouseover' && $(this).find('textarea').length == 0 ) {
	 * $button.show(); $(this).addClass('highlight'); } else { $button.hide();
	 * $(this).removeClass('highlight'); }
	 * 
	 * });
	 * 
	 * $('a.editContentButton').live( 'click', function(e) {
	 * 
	 * e.preventDefault();
	 * 
	 * var $this = $(this); var $parent = $(this).parent(); // find the stuff we
	 * need var regex = /([\w_]+)_([0-9]+)_([\w]+)/i; var id =
	 * $parent.attr('id'); result = regex.exec(id); //console.debug(result); if (
	 * result != null ) {
	 * 
	 * $this.remove(); var defaultWidth = $parent.width(); var defaultHeight =
	 * $parent.height(); // copy the content var oldContent = $parent.html();
	 * var newContent = oldContent;
	 * 
	 * 
	 * var dataSource = result[1]; var recordId = result[2]; var field =
	 * result[3];
	 *  // remove the old content $parent.removeClass('highlight').html('');
	 * $parent.append( $('<form></form>', { 'method' : 'post' }).append( $('<fieldset></fieldset>').append(
	 * $('<textarea></textarea>',{ width: defaultWidth, height:
	 * defaultHeight+30, 'id' : id+'Editor' }).after( $('<input></input>',{
	 * 'type' : 'submit', 'value' : 'Save', 'class' : 'submit' }).after( $('<input></input>',{
	 * 'type' : 'submit', 'value': 'Cancel', 'class' : 'submit' }).bind(
	 * 'click', function(e) { e.preventDefault(); var $parentDiv =
	 * $(this).parent().parent().parent(); $parentDiv.html(oldContent);
	 * $parentDiv.append( $('<a></a>',{ 'class' : 'editContentButton', 'href' :
	 * 'javascript:', html : 'edit text' })); }))))));
	 * $parent.find('textarea').val(oldContent); if (
	 * $parent.hasClass('editableMCE') ) { // edit with tinyMCE tinyMCE.init({
	 * mode : 'exact', elements : id+'Editor', theme: 'advanced', body_class:
	 * 'cms', content_css : '/styles/cms.css', plugins:
	 * "safari,inlinepopups,paste,table", theme_advanced_buttons1 : "bold,
	 * italic, underline, justifyleft,justifycenter, justifyright, justifyfull ,
	 * formatselect, |, pasteword, pastetext, code", theme_advanced_buttons2 :
	 * "undo,redo,|,bullist, numlist,|,outdent,indent, |, link, unlink ",
	 * theme_advanced_buttons3 : "tablecontrols", theme_advanced_resizing :
	 * true, theme_advanced_toolbar_location : "top",
	 * theme_advanced_toolbar_align : "center",
	 * theme_advanced_statusbar_location : "bottom", theme_advanced_blockformats :
	 * "p,h2,h3,h4", table_row_styles : "Light=row_a;Dark=row_b", convert_urls :
	 * false, verify_html : true, valid_elements :
	 * "@[class|style|title],br,h2,h3,h4,-p[align],-strong/b,a[name|href|target],"+
	 * "img[src|border=0|alt|title|width|height|align],hr[width|size|noshade],"+
	 * "table[border|cellspacing|cellpadding|width],tr[rowspan],td[colspan],th[colspan],-ul,ol,-li",
	 * setup : function(ed) { ed.onSaveContent.add(function(ed, o) { newContent =
	 * o.content; }); ed.onSubmit.add(function(ed, e) { e.preventDefault(); //
	 * hide form and show saving animation $(e.target).replaceWith( $('<div></div>',{
	 * width: defaultWidth, height: defaultHeight }).css({ 'text-align' :
	 * 'center', 'font-size' : '10px', 'background' : 'rgba(99,99,99,.2)'
	 * }).append( $('<img />',{ 'src' : '/images/ajax_saving.gif', 'alt' : '',
	 * 'style' : 'margin-top: '+((defaultHeight/2)-10)+'px' }) ).append( $('<br />')
	 * ).append( $('<span></span>',{ html: 'saving text...' })));
	 * 
	 * saveEdit($parent,dataSource,recordId,field,newContent);
	 * 
	 * }); } }); } else { // edit in textarea so add the on submit event
	 * $parent.find('form').bind('submit',function(e) { e.preventDefault();
	 * newContent = $(this).find('textarea:eq(0)').val();
	 * saveEdit($parent,dataSource,recordId,field,newContent); }); } }
	 * 
	 * }); // the ajax save function var saveEdit =
	 * function($parent,dataSource,id,field,newContent) { // now save with ajax
	 * $.ajax({ url: '/lib/ajax/saveInlineEdit.php', cache: false, type: 'POST',
	 * dataType: 'json', data : { 'dataSource' : dataSource, 'id' : id, 'field' :
	 * field, 'data' : newContent }, error : function(XMLHttpRequest,
	 * textStatus, errorThrown){ $parent.find('div').css({ 'background' :
	 * '#b00', 'color' : '#fff' }).html( $('<span></span>',{ html : 'Failed to
	 * save, new content will be displayed, please click edit and attempt to
	 * save again' })); setTimeout(function() { $parent.fadeOut(100,function() {
	 * $parent.html(newContent); $parent.fadeIn(100,function() { $parent.append(
	 * $('<a></a>',{ 'class' : 'editContentButton', 'href' : 'javascript:',
	 * html : 'edit text' })); }); }); },5000); }, success : function(data,
	 * textStatus) { $parent.html(newContent); $parent.append( $('<a></a>',{
	 * 'class' : 'editContentButton', 'href' : 'javascript:', html : 'edit text'
	 * })); } }); }; // add the edit buttons
	 * $('div.editableMCE,div.editableText').append( $('<a></a>',{ 'class' :
	 * 'editContentButton', 'href' : 'javascript:', html : 'edit text' }));
	 */

	// voucher code edit button
	$('#btnChangeVoucherCode').bind('click', function(e) {

		var $button = $(this);
		var $parent = $button.parent();
		var $input = $parent.children('input[type="hidden"]');
		var currentCode = $input.val();

		// remove the hidden field and button
		$input.remove();
		$button.remove();

		// create the new text input
		var $newInput = $('<input />', {
		    name : 'voucherCode',
		    type : 'text',
		    id : 'voucherCode',
		    value : ''
		});

		// add the input
		$parent.append($newInput);

		// update the help text
		$parent.children('p').text('Please enter another promotional code here...');

	});

});

// tinyMCE configuration
tinyMCE.init({
    mode : "specific_textareas",
    editor_selector : "tiny_mce",
    theme : "advanced",
    editor_deselector : "mceNoEditor",
    body_class : "cms",
    content_css : "/styles/cms.css",
    plugins : "safari,inlinepopups,paste,table",
    width : "524",
    height : "500",
    theme_advanced_buttons1 : "bold, italic, underline, justifyleft,justifycenter, justifyright, justifyfull , formatselect,  |, pasteword, pastetext, code",
    theme_advanced_buttons2 : "undo,redo,|,bullist, numlist,|,outdent,indent, |, link, unlink ",
    theme_advanced_buttons3 : "tablecontrols",
    theme_advanced_resizing : true,
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "center",
    theme_advanced_statusbar_location : "bottom",
    theme_advanced_blockformats : "p,h2,h3,h4",
    table_row_styles : "Light=row_a;Dark=row_b",
    convert_urls : false,
    verify_html : true,
    valid_elements : "@[class|style|title],br,h2,h3,h4,-p[align],-strong/b,a[name|href|target]," + "img[src|border=0|alt|title|width|height|align],hr[width|size|noshade]," + "table[border|cellspacing|cellpadding|width],tr[rowspan],td[colspan],th[colspan],-ul,ol,-li"
});

