// Some global variables.
var open = false;

var sampleUIInterval = 0;
var languageListInterval = 1;
var sampleUpdateInterval = 2;


// Inserts CSS rules for JS-only in head.
function AppendJSCSS() {

    "use strict";

    var url = '/v7/js.css';

    // If IE8, use CreateStyleSheet().
    if(($.browser.msie === true) && (parseInt($.browser.version, 10) === 8)) {

	document.createStyleSheet(url);

	return true; 

    }

    //    $('head').append('<link href="/v7/js.css" rel="stylesheet" type="text/css" media="screen">');

    $('link[href="/v7/site.css"]').after('<link href="' + url + '" rel="stylesheet" type="text/css" media="screen">');
  

}


// Function to increment or decrement value of element by 1, and return new value to element.
function stepElementValue(element, direction, min, max) {

    "use strict";

    // Convert string to integer.
    var inputVal = parseInt(element.val(), 10);

    // Test for bad value; reset to minimum if found.
    if (isNaN(inputVal) === true) { element.val(min.toString()); return false; }

    // Basic validation. (How does HTML5 handle this?)
    // Min decrement: no action.
    if ((inputVal === min) && (direction === 0)) { return false; }
    // Max increment: no action.
    if ((inputVal === max) && (direction === 1)) { return false; }
    // Already below min: reset to min.
    if (inputVal < min) { element.val(min.toString()); return false; }
    // Already above max: reset to max.
    if (inputVal > max) { element.val(max.toString()); return false; }

    // Increment or decrement.
    if (direction === 0) { inputVal--; } else if (direction === 1) { inputVal++; }

    // Convert modified value to string; write to element.
    element.val(inputVal.toString());

} // End of function stepElementValue.


function basketAmounts() {

    "use strict";

    // Is this even necessary? Isn't it supposed to be just a link? (Might be worth doing anyway.)

    $('#basketsummary a.less').bind('mousedown', function (e) {

	// Left button click only.
	if (e.which === 1){

	    // Get input element that this button relates to.
	    var inputElement = $(this).parent().children('input');

	    // Decrement element's value with appropriate min/max values..
	    stepElementValue(inputElement, 0, 5, 50000);

	}

    });

    $('#basketsummary a.more').bind('mousedown', function (e) {

	// Left button click only.
	if (e.which === 1){

	    // Get input element that this button relates to.
	    var inputElement = $(this).parent().children('input');

	    // Or increment. (Could mash this in to one bind to save a few lines.)
	    stepElementValue(inputElement, 1, 5, 50000);
	
	}

    });

} // End of function basketAmounts.


function basketDecoration() {

    "use strict";

    $('#basketsummary tr.product form.remove').hover(function (){

	    $(this).parent().parent().addClass('hover');
	    $(this).parent().parent().parent().next('tr.users').children('td').addClass('hover');

    }, function (){

	    $(this).parent().parent().removeClass('hover');
	    $(this).parent().parent().parent().next('tr.users').children('td').removeClass('hover');

    });

} // End of function basketDecoration.


function FilterLanguageList() {

    "use strict";

    // Inject appropriate markup. (Move all this elsewhere!)
    var myNewMarkup = '<div id="language-list-filter"><span class="clear-text"></span><input type="text" placeholder="Search for a language..."></div>';
    // Insert before <ul>
    $('#language-list').before(myNewMarkup);

    // Filter language list on family page.
    var myPattern = '', myRegExp;

    var watchElement = $('#language-list-filter input');

    //    watchElement.die('focus');
    watchElement.live('focus', function() {

	languageListInterval = setInterval(function(){ 
	    // Show "enabled" clear icon if there's text present.
	    updateLanguageList(watchElement);
	}, 100);

    });

    //    watchElement.die('blur');
    watchElement.live('blur', function() {

	clearInterval(languageListInterval);

    });

    $('#language-list-filter span.clear-text-enabled').live('mousedown', function(e) {

	    // Left click only.
	    if (e.which === 1){

		$(this).siblings('input').val('');
		$(this).siblings('input').trigger('focus');

	    }

	});

} // End of function filterLanguageList.


function updateLanguageList(element) {

    myPattern = element.val();

    myRegExp = new RegExp('^' + myPattern,'i');

    $('#language-list li.list ul li').each(function() {

	// If input is blank, remove all filter classes.
	if (myPattern === '') {
	    $(this).removeClass('filter-false');
	    $(this).removeClass('filter-true');
	    return;
	}

        var myString = $(this).text();

        if (myRegExp.test(myString) === false) {
	    // Filter doesn't match.
	    $(this).addClass('filter-false');
	    $(this).removeClass('filter-true');
	} else {
	    // Filter matches.
	    $(this).addClass('filter-true');
	    $(this).removeClass('filter-false');
	}

    });
    // End of each function.

    if (element.val() !== ''){

	element.parent().children('span.clear-text').addClass('clear-text-enabled');

    } else {

	element.parent().children('span.clear-text').removeClass('clear-text-enabled');

    }

    return true;

} // End of function updateLanguageList.


function toggleEditions() {

    "use strict";

    var editionsHidden = false;

    // Toggle editions on family page.
    $('.hide-editions').bind('click', function () {

	if (editionsHidden === false){
	
	    $('#grid-header').addClass('grid-header-no-background');
	    $('#editions-header').hide();

	    // Get height of purchase grid tr and apply before hiding buttons.
	    var currentHeight = $('#purchase tr').height();
	    // Take one pixel off? Temporary hack!
	    currentHeight--;
	    $('#purchase tr').css('height', currentHeight);
	
	    $('td.price').hide();
	    // $('#purchase td.sample').toggleClass('full-width-sample');
	    $('.hide-editions').children('span.arrow').addClass('hidden');

	    editionsHidden = true;

	} else {

	    $('#grid-header').removeClass('grid-header-no-background');
	    $('#editions-header').show();

	    // Set tr height back to auto so smaller (or larger) samples fit properly.
	    $('#purchase tr').css('height', 'auto');
	
	    // Just a test.
//	    $('#purchase td.sample img').attr('src','http://2011m1.dmcd.net/renderengine/sample?b=FFFFFF&f=dama%2FFoco_Std_Lt.ttf&w=784&h=18');

	    $('td.price').show();
	    $('.hide-editions').children('span.arrow').removeClass('hidden');

	    editionsHidden = false;

	}

	// Could sanely move this into if block.
	var txt = $(this).children('span.text').text();

	if (txt === 'Hide editions') { $('.hide-editions').children('span.text').text('Show editions'); } else { $('.hide-editions').children('span.text').text('Hide editions'); }
	//

	return false;

    });

} // End of function toggleEditions.


function sampleUI() {

    "use strict";

    // Temporary: hide submit button. (Do with CSS later.)
    $('#sample-control-form input[type=submit]').hide();

    // var watchElement = $('#sampleText');

    // watchElement.bind('focus', function() {

    // 	sampleUIInterval = setInterval(function(){ 
	    // Show "enabled" clear icon if there's text present.
    // 	    updateSampleUI(watchElement);
    // 	}, 100);

    // });

    // watchElement.bind('blur', function() {

    // 	clearInterval(sampleUIInterval);

    // });

    // Add clear-text markup (not done).
    //<span class=\"clear-text\">[X]</span>

    // Clear sample text input when "X" is clicked.
    //    $('#sample-control-text span.clear-text-enabled').live('mousedown', function(e) {

	    // Left click only.
    //	    if (e.which === 1){

    //		$(this).siblings('input').val('');
    //		$(this).siblings('input').trigger('focus');

    //	    }

    //	});


    // Timed updates.
    //    $('#sampleText').unbind('focus keyup mouseup');
    $('#sampleText').bind('focus keyup mouseup', function() {

	    clearTimeout(sampleUpdateInterval);

    	    // Interval after inactivity on inputs, then call update.
	    sampleUpdateInterval = setTimeout(function() {
		    UpdateSampleText();
		}, 500);

    	});

    // Enter = immediate update.
    //    $('#sampleText').unbind('keydown');
    $('#sampleText').bind('keydown', function(e) {

	    if (e.which === 13){
		UpdateSampleText();
		return false;
	    }

	});

    // If type=range isn't supported for sampleSize, replace with select.
    if ($('#sampleSize').prop('type') === 'text'){

	var inputOnChange = $('#sampleSize').attr('onchange');
	var inputValue = parseInt($('#sampleSize').val(), 10);

	// var mySizeList = new Array(
	// 			   16,
	// 			   18,
	// 			   21,
	// 			   24,
	// 			   36,
	// 			   40,
	// 			   48,
	// 			   60,
	// 			   72,
	// 			   100,
	// 			   150,
	// 			   200
	// 			   );

	var mySizeList = new Array(
				   16,
				   17.6,
				   19.2,
				   22.4,
				   25.6,
				   28.8,
				   32,
				   38.4,
				   44.8,
				   48,
				   51.2,
				   57.6,
				   70.4,
				   76.8,
				   96,
				   115.2,
				   128,
				   140.8,
				   153.6,
				   166.4,
				   179.2,
				   192,
				   200
				   );

	// Sensible default. Required just in case there's no starting cookie?
	var myNearest = 40;

	// Validation: only look for a closest-match if the original value is valid.
	if ((inputValue >= 16) && (inputValue <= 200)){

	    // The "current closest result" gets set before we start looping. (Because they're ordered, it's the first item.)
	    var myClosest = Math.abs(mySizeList[0] - inputValue);

	    // If 16-200, go through each number in list above.
	    $.each(mySizeList, function(e){

		    // If the current value (from the <select>) exactly matches a value in this list, use that.
		    // (This should be the most common outcome. Users without type=range won't get an alternative value to begin with.)
		    if (inputValue === mySizeList[e]){

			myNearest = mySizeList[e];

			// Quit the loop; we've got the result.
			return false;

		    } else {

			// If there's no exact match, do some maths. All negative values get converted to positive.
			var myDifference = Math.abs(mySizeList[e] - inputValue);

			// If the difference between the input and the current value (statically defined above) is LESS than "last time", set the result to the current value. (Remember, on the first iteration, "last time" is just the lowest possible difference. Because these are ordered in terms of size, that's the first item.
			if (myDifference < myClosest){
			    myNearest = mySizeList[e];
			}

			// If there is no difference, it's because we're exactly halfway between two possibilities. Get the last match -1.
			if (myDifference === myClosest){
			    myNearest = mySizeList[e-1];
			}

			// Update the check thinger.
			myClosest = myDifference;

		    }

		});

	}
	// End of if 16-200.

	var newMarkup = '<select onchange="' + inputOnChange + ' ResizeSamples()" id="sampleSize">';

	// Go through pre-set size list, print markup.
	$.each(mySizeList, function(e){

		newMarkup += '<option value="' + Math.round(mySizeList[e]) + '"';

		var myLabel = Math.round(mySizeList[e] / 1.6);

		myLabel.toString();

		if (mySizeList[e] === myNearest){

		    newMarkup += ' selected="selected"';

		}

		newMarkup += '>' + myLabel + 'pt</option>';

	    });

	newMarkup += '</select>';

	$('#sampleSize').remove();
	
	$('#samplesize-container').append(newMarkup);
	

    } else if ($('#sampleSize').prop('type') === 'range'){

	// Insert presentational small-A/big-A either side of range slider.
	$('#samplesize-container').addClass('range-available');
	$('#sampleSize').before('<span class="smaller">A</span>');
	$('#sampleSize').after('<span class="larger">A</span>');
	
    }
    // End of if prop=text/range


    // Temporary: attach update functions to certain input events.
    // $('#sampleSize').bind('mouseup', function() {
    // 	    ResizeSamples();
    // 	});
    // $('#sampleSize').bind('change', function() {
	    
    // 	});

} // End of function sampleUI.


function ResizeSamples() {

    "use strict";

    $('.sampleimg').trigger('updateimg');

}

function UpdateSampleText() {

    "use strict";

    var sampleText = $('#sampleText').val();

    $('.sampleimg').trigger('updateimg');

    document.cookie = 'sampletext=' + encodeURIComponent(sampleText) + '; path=/; domain=daltonmaag.com';

    return false;

}
// End of function UpdateSampleText.

function UpdateSampleSize(width) {

    "use strict";

    var sampleSize = $('#sampleSize').val() + 'px';

    document.cookie = 'samplesize=' + sampleSize + '; path=/; domain=daltonmaag.com';

    $('.sampleimg').css('height', sampleSize);
    $('.samplecontainer').css('height', sampleSize);
    $('.samplecontainer').css('width', width + 'px');
    $('.samplecontainer').css('overflow', 'hidden');

    $('.samplecontainer a').css('height', sampleSize);
    $('.samplecontainer a').css('width', width + 'px');

    return false;

}
// End of function UpdateSampleSize.


function updateSampleUI(element) {

    "use strict";

    // Not appropriate to check for value; check for text (because the value is in markup, supplied by cookie).
    if (element.val() !== ''){

	element.parent().children('span.clear-text').addClass('clear-text-enabled');

    } else {

	element.parent().children('span.clear-text').removeClass('clear-text-enabled');

    }

} // End of function watchSampleInput.


function fixedSampleGridUI() {

    "use strict";

// Get a reference to the placeholder. This element
// will take up visual space when the message is
// moved into a fixed position.
/*
var placeholder = $( "#site-message-placeholder" );
*/ 

// Get a reference to the message whose position
// we want to "fix" on window-scroll.
/*
var message = $( "#site-message" );
*/ 

// Get a reference to the window object; we will use
// this several time, so cache the jQuery wrapper.
/*
var view = $( window );
*/ 

 
// Bind to the window scroll and resize events.
// Remember, resizing can also change the scroll
// of the page.
/*
view.bind(
"scroll resize",
function(){
*/

// Get the current offset of the placeholder.
// Since the message might be in fixed
// position, it is the plcaeholder that will
// give us reliable offsets.
/*
var placeholderTop = placeholder.offset().top;
*/ 

// Get the current scroll of the window.
/*
var viewTop = view.scrollTop();
*/ 

// Check to see if the view had scroll down
// past the top of the placeholder AND that
// the message is not yet fixed.
/*
if (
(viewTop > placeholderTop) &&
!message.is( ".site-message-fixed" )
){
*/
 
// The message needs to be fixed. Before
// we change its positon, we need to re-
// adjust the placeholder height to keep
// the same space as the message.
//
// NOTE: All we're doing here is going
// from auto height to explicit height.
/*
placeholder.height(
placeholder.height()
);
*/ 

// Make the message fixed.
/*
message.addClass( "site-message-fixed" );
*/ 

// Check to see if the view has scroll back up
// above the message AND that the message is
// currently fixed.
/*
} else if (
(viewTop <= placeholderTop) &&
message.is( ".site-message-fixed" )
){
*/
 
// Make the placeholder height auto again.
/*
placeholder.css( "height", "auto" );
*/ 

// Remove the fixed position class on the
// message. This will pop it back into its
// static position.
/*
message.removeClass( "site-message-fixed" );
 
}
}
);
*/

}

function openDropDown(element) {

    "use strict";

    element.children('div.dropdown').show();
    //    element.children('div.select').addClass('select-open');
    element.addClass('select-open');

    // Remove the hovered state from selected list items in the dropdown, when the mouse passes over any other. (This apes some OS-style UI behaviour, maybe unnecessarily.)
    element.find('div.dropdown li').bind('mouseover', function(){
	    element.find('div.dropdown li.selected-hover').removeClass('selected-hover');
    });

} // End of function openDropDown.

function closeDropDown(element) {

    "use strict";

    element.children('div.dropdown').hide();
    //    element.children('div.select').removeClass('select-open');
    element.removeClass('select-open');

    // Unbind; re-add the hover class (which is initially only added at markup inject, so gets lost).
    element.find('div.dropdown li').unbind('mouseover');
    element.find('div.dropdown li.selected').addClass('selected-hover');

    $(document).unbind('mousedown');
    open = false;


} // End of function closeDropDown.

function closeDropDownExcept(element) {

    "use strict";

    // Ugh, hacky. Fix. Could make a list of those called in pageLoaded()?
    $('div.dropdown').parent().not(element).each(function(){
	    closeDropDown($(this));
	});

    // Works OK, but seems to take two clicks atm..not dreadful.

}
// End of function closeDropDownExcept.

// Fancy select dropdowns.
function selectDropDown(element) {

    "use strict";

    element.find('select').hide();

    var selectedItemText = element.find('select option:selected').text();

//    var selectedItemVal = $(element + ' select option:selected').val();

    var newMarkup = '<div class="select">\n' + selectedItemText + '<span class="dropdown-arrow"></span>\n</div>\n<div class="dropdown">\n<ul>\n';

    var selectName = element.find('select').attr('name');
    //    console.log(element.attr('name'));

    // Rewrite each <option> as <li> item.
    element.find('select option').each(function(){

	var label = $(this).text();
	var value = $(this).val();
	var selected = $(this).attr('selected');

	// Not sure we want selected item to appear in dropdown.
	//if (selecte>d === 'selected'){ return true; }

	newMarkup += '<li';

	// If you want the selected item to appear in the dropdown, use:
	if (selected === 'selected'){
	    newMarkup += ' class="selected selected-hover"';
	}

	newMarkup += '><a href="#">' + label + '</a><input type="hidden" name="' + selectName + '" value="' + value + '"></li>\n';

    });
    // End of option.each

    newMarkup += '</ul>\n</div>\n';

    // Remove select now. Better time? e.g. could detatch before .each, if .each could operate on detatched element?
    element.find('select').remove();

    // When all the replacement markup is ready (via iterations), append to master element.
    element.append(newMarkup);

    // Bind replaced-option click with form submit stuff.
    element.find('div.dropdown li a').bind('click', function(e) {

	    // Left click only.
	    if (e.which === 1){

		closeDropDown(element);

		// We already know this.
		//var selectedName = $(this).siblings('input').attr('name'));

		// Not necessarily necessary. Just remove all the other inputs. Too heavy?
		//var selectedValue = $(this).siblings('input').val();

		//		$(this).parent().parent().find('input').not($(this)).remove();

		$(this).parent().parent().find('input').not($(this).siblings('input')).each(function() {
			$(this).remove();
		    });

		element.submit();

		return false;

	    }

    });

    // Convoluted: make sure clicks on the selected item don't do anything (Except close the dropdown, and pass the selected option on.)
    element.find('div.dropdown li.selected a').bind('click', function() {
	return false;
    });


//    var open = false;

    element.bind('mousedown', function(e){

	// Left click only.
	if (e.which === 1){

	    // If the dropdown is closed:
	    if (open === false){

		// Need to add something here to make sure a click on one closes any other open ones.
		closeDropDownExcept(element);

		// Open it (but passing the specific element, not the selector),
		openDropDown(element);

		// ensure that a click anywhere else will close it,
		$(document).bind('mousedown', function(){
			closeDropDown(element);
		});

		//    console.log( $(element + ' div.dropdown').css('overflow') );


		// and flag it as open.
		open = true;

	    } else {

		closeDropDown(element);

	    }

	    // This element is naturally included in $(document), so make sure that events don't bubble up.
	    e.stopPropagation();

	}

    });

    element.children('div.dropdown').bind('mousedown', function(){
	return false;
    });


    // If the dropdown has overflow:auto, and a user scroll-wheels over it, make sure that this event doesn't scroll the browser window IF the <ul> is at the top or the bottom of the <div>. (Return false?)
    element.children('div.dropdown').bind('mousewheel', function(event, delta){

	    //console.log('dropdown scroll');

	    // Hacky attempt. ;-)
	    // $(window).bind('mousewheel', function(e){
	    // 	    console.log('window scroll attempt');
	    // 	    e.preventDefault();
	    // 	});


	    var overflow = $(this).css('overflow');
	    var listTop = ($(this).children('ul').position()).top;
	    var listHeight = $(this).children('ul').outerHeight();
	    var dropdownHeight = $(this).outerHeight();
	    var listStop = listHeight - dropdownHeight;
	    var listTopStop = Math.round(Math.abs(listTop));

	    // Only for dropdowns that *can* scroll.
	    if (overflow === 'auto'){

	     	// console.log(listTop + ' | ' + delta);

		// Is ul at 0 and we're scrolling up? Is ul at x and we're scrolling down?
    		if ( ( (listTop === 0) && (delta > 0) ) || ( (listTopStop === listStop) && (delta < 0) ) ){ 

		    // Don't scroll.
    		    event.preventDefault();

    		}

    	    }

	});
    // Done, but could the occasional erroneous window scroll events be avoided?


    // Testing stuff.
    // $(element + ' div.dropdown').children().bind('mousewheel', function(event){
    // 	    console.log('child scroll event');
    // 	});

    // $(window).bind('scroll', function(e){
    // 	    console.error('window scroll');
    // 	});


}
// end of function selectdropdown.

function ToggleLoginPasswordDisabled() {

    // Run the below checker on page load, and when one is clicked
   
    // $('.loginbox input[name=login_intent]').bind('mouseup', function(){
	    
    // 	});


    // if ($(this).val() === 'password'){
	
    // 	$('.loginbox input[name=login_password]').attr('disabled','disabled');
	
    // } else {
	
    // 	$('.loginbox input[name=login_password]').removeAttr('disabled');
	
    // }

}


function ReplacePlaceholders() {

    // Temp: don't do for IE8
    // if(($.browser.msie === true) && (parseInt($.browser.version, 10) === 8)) {
    // 	return false; 
    // }

    // If the browser supports placeholder attr, do nothing. If not, set appropriate stuff on element.

    // Extend jQuery's support object.
    $.extend($.support, {

	    placeholder : function() {

		//		var myTest = $('input[placeholder!=""]').first();

		// Testing against an existing element with this property seems unreliable. Use plain JS to insert.
		var myTest = document.createElement('input');

		if ('placeholder' in myTest) {
		    return true;
		} 

		return false;

	    }

	});

    if ($.support.placeholder() === false){

	// Replace the value on these elements with the placeholder text; make this disappear when they have focus and aren't blank.

	$('input').each(function() {

		// Store placeholder text in variable.
		var myPlaceholder = $(this).attr('placeholder');
		var myVal = $(this).val();

		// Check for placeholder attr.
		if (typeof(myPlaceholder) !== 'undefined'){
	    
		    // temp
		    $(this).parent().css('position', 'relative');
		    var myPaddingTop = $(this).parent().css('padding-top');
		    var myPaddingLeft = $(this).parent().css('padding-left');
		    
		    // Create placeholder element and position correctly.
		    //		    var myNewMarkup = '<label class="placeholder" style="top:' + myPaddingTop + '; left:' + myPaddingLeft + '; width:' + $(this).css('width') + '; height:' + $(this).outerHeight() +'px;">' + myPlaceholder + '</label>';
		    //		    var myNewMarkup = '<label class="placeholder" style="width:' + $(this).width() + 'px; height:' + $(this).height() +'px;">' + myPlaceholder + '</label>';
		    var myNewMarkup = '<span class="placeholder">' + myPlaceholder + '</span>';

		    // could there be a problem with this in IE8? the problem seems to be that the created element doesn't actually get any styles.. it's probably to do with how the jquery is first called, and the order of things (CSS, injects, etc.)
		    $(this).parent().append(myNewMarkup);

		    // Check for value: if it's blank, show the placeholder.
		    if (myVal === ''){
			$(this).siblings('.placeholder').css('display', 'block');
		    }

		    // Get rid of the placeholder when it's clicked on, and give focus to underlying input. Restore placeholder if input is empty.
		    $('.placeholder').live('mousedown', function() {
			    
			    $(this).hide();
			    $(this).siblings('input[type=text]').trigger('focus');
			    
			});

		    // IE9 fix, perhaps temporary.
		    $(this).bind('mousedown', function() {

			    //			    alert($(this).siblings('.placeholder').css('display'));

			    if ($(this).siblings('.placeholder').css('display') !== 'none'){

			    	$(this).siblings('.placeholder').hide();
				
			    }

			});

		    $(this).bind('blur', function() {
			    
			    if ($(this).val() === ''){
				
				$(this).siblings('.placeholder').show();
				
			    }
			    
			});

		}
		// End of if typeof.

	    });

    }
    // End of if placeholder = false.

}
// End of function ReplacePlaceholders.


function EmptyBasketConfirm() {

    "use strict";

    var myPromptMarkup = '<div class="prompt">Empty basket. Are you sure? <input type="submit" value="Yes, empty."><input type="submit" value="No, cancel."></div>';

    // Careful of this when it comes to AJAX.
    $('#basketsummary form.empty').bind('submit', function(e){

	    $(this).after(myPromptMarkup);

	    return false;

	});

}
// End of function EmptyBasketConfirm.


function Slideshow(imgArray) {

    "use strict";

    // How to make this generic? Might need to work out where it's being "called from".
    // Temporary: select directly here (could make an array of possible slideshows and test for existence, bit annoying to maintain -- though I suppose that'd be the case without markup <script> too.

    // Preload images.
    $.each(imgArray, function(e){ 

	    $('#portfolio-image').append('<img src="' + imgArray[e] + '" style="display:none;" class="preload">');

	});

    $('#portfolio-image img.preload').remove();


    var myNewMarkup = '<div class="slideshow-ui" style="position:absolute; bottom:0; right:0;">';

    $.each(imgArray, function(e){ 

	    //	    myNewMarkup += '<a href="' + imgArray[e] + '">' + (e+1) + '</a>';
	    myNewMarkup += '<a href="' + imgArray[e] + '"';
	    
	    if (e === 0){ myNewMarkup += ' class="selected"'; }

	    myNewMarkup += '><span></span></a>';

	});

    myNewMarkup += '</div>';

    $('#portfolio-image').append(myNewMarkup);

    $('#portfolio-image .slideshow-ui a').bind('mousedown', function(e) {

	    // Left click only.
	    if (e.which === 1){

		//		var myImgElement = $(this).parent().parent().children('img');

		//		myImgElement.attr('src', $(this).attr('href'));

		$(this).parent().parent().children('img').attr('src', $(this).attr('href'));
		$(this).parent().children('a').removeClass('selected');
		$(this).addClass('selected');

	    }

	    // Return false either way.
	    return false;

	});

    $('#portfolio-image .slideshow-ui a').bind('click', function() {

	    return false;

	});

}
// End of function Slideshow.


// Function for everything when the document is loaded.
function pageLoadedTmp() {

    "use strict";

    AppendJSCSS();

    // Not ready just yet.
    // Pass the element, not the selector.
    //selectDropDown($('#language'));
    //selectDropDown($('#currency'));
    //$('#basketsummary tr.users form').each(function() {
    //	    selectDropDown($(this));
    //	});
    $('#language select, #currency select, #basketsummary tr.users form select').bind('change', function() {
	    $(this).parent().submit();
	});


    basketAmounts();

    FilterLanguageList();

    toggleEditions();

    basketDecoration();

    sampleUI();
    // Make sure sample input clear-button is styled appropriately at load.
    updateSampleUI($('#sampleText'));

    ToggleLoginPasswordDisabled();

    // EmptyBasketConfirm();

    // (Has to come after we inject some inputs.)
    // Temporary: ignore if IE8
    ReplacePlaceholders();

} // End of function pageLoaded.

//temporary
$(document).ready(function() {
	pageLoadedTmp();
   });
// function pageLoaded() {
//        "use strict";
//        return false;
//     }

// $(window).load(function() {

// 	AppendJSCSS();

//     });


//From site.js:
function CollectiveFormCheck($id){

    "use strict";

    $('#confirm' + $id).hide();
    $('#download' + $id).hide();
    $('#again$' + $id).hide();

    if(parseInt($('#num' + $id).val(),10)>=0){

	$('#confirm' + $id).show();

	if($('#check' + $id + ':checked').length > 0){

	    /* $('#num' + $id).attr('disabled', true); */
	    $('#download' + $id).show();

	} else {

	    /* $('#num' + $id).attr('disabled', false); */

	}

    }

}

function InvalidateCollectiveForm($id){

    "use strict";

    $('#blurb' + $id).hide();
    $('#confirm' + $id).hide();
    $('#download' + $id).hide();
    $('#again' + $id).show();

}

