var init = true;
function debug (debugValue) {
	//alert(debugValue);
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

// The SKU item object
function AlternativeImage (name, altText, smallImage, largeImage, hugeImage) {
	this.name = name;
	this.altText = altText;
	this.smallImage = smallImage;
	this.largeImage = largeImage;
	this.hugeImage = hugeImage;
}

AlternativeImage.prototype.getName = function() {return this.name;};
AlternativeImage.prototype.getAltText = function() {return this.altText;};
AlternativeImage.prototype.getLargeImage = function() {return this.largeImage;};
AlternativeImage.prototype.getHugeImage = function() {return this.hugeImage;};
AlternativeImage.prototype.getSmallImage = function() {return this.smallImage;};

function SkuAlternativeImages () {
	this.array = new Array();
}

SkuAlternativeImages.prototype.put = function( alternativeImage ) {
    if( ( typeof alternativeImage != "undefined" ) ) {
        this.array[this.array.length] = alternativeImage;
    }
}

function Price (nowPrice, wasPrice, savingPercentage, savingAmount, showWasPricePercentage, showWasPriceAmount ) {
	this.nowPrice = nowPrice;
	this.wasPrice = wasPrice;
	this.savingAmount = savingAmount;
	this.savingPercentage = savingPercentage;
	this.showWasPricePercentage = showWasPricePercentage;
	this.showWasPriceAmount = showWasPriceAmount;
}

Price.prototype.getNowPrice = function() {return this.nowPrice;};
Price.prototype.getWasPrice = function() {return this.wasPrice;};
Price.prototype.getSavingAmount = function() {return this.savingAmount;};
Price.prototype.getSavingPercentage = function() {return this.savingPercentage;};
Price.prototype.getShowWasPricePercentage = function() {return this.showWasPricePercentage;};
Price.prototype.getShowWasPriceAmount = function() {return this.showWasPriceAmount;};

function SkuSettings (price, alternativeImages) {
	this.alternativeImages = alternativeImages;
	this.price = price;
}

SkuSettings.prototype.getPrice = function() {return this.price;};
SkuSettings.prototype.getAlternativeImages = function() {this.alternativeImages;};

//SkuSettings.prototype.put = function(alternativeImages, prices);

// KeyValue - Defines the keys for our hashmap
function KeyValue( key, value) {
    this.key = key;
    this.value = value;
}

// Map - defines the hash map array
function Map() {
    this.array = new Array();
}

Map.prototype.put = function( key, value ) {
    if( ( typeof key != "undefined" ) && ( typeof value != "undefined" ) ) {
        this.array[this.array.length] = new KeyValue( key, value);
    }
}

Map.prototype.get = function( key ) {

	debug("map.get('" + key + "'");
    for( var k = 0 ; k < this.array.length ; k++ ) {
    	debug("checking specified key[" + key + "] against stored key[" + this.array[k].key + "]");
        if( this.array[k].key == key ) {
	    	debug("found specified key[" + key + "]");
            return this.array[k].value;
        }
    }
    return "";
}

Map.prototype.length = function() {
    return this.array.length;
}



// On initial load we re move the options from the sub-options until user has selected previous option
function initOptions(multipleProducts) {

	var dealingWithRadioButtons = false;

	// reset the diouble click variable
	
	// If this is a page with multiple products then we need to ensure we set all possible dropdowns
	var maxNoOfProducts = 1;
	var maxNoOfOptions = 10;
	var displayPriceLabel  = true;
	if (multipleProducts) {
		maxNoOfProducts = 10;
		displayPriceLabel  = false;
	}

	// Iterate through each product on the page (Assumes max of 10 for say a bundle/quick shop page)
	for (prodIdx = 0; prodIdx < maxNoOfProducts; prodIdx++) {
		var productPrefix = "";
		if (maxNoOfProducts > 1) {
			productPrefix = "p" + prodIdx;
		}

		var lastSelectedId  = "";	
		var lastSelectedElement  = "";	
		var lastSelectedOptionNo = 0;
		
		var previousSelected = false;
		// Iterate through each drop down box and check if it has a selected option
		for (initIdx = 1; initIdx <= maxNoOfOptions; initIdx++) {
			var elementId = productPrefix + "attrValue" + (initIdx);		
			
			if (document.getElementById(elementId)) {
				var definingOption = document.getElementById(elementId);
				if (definingOption != "undefined") {
				
					// We assume we have a set of Select boxes used for the defining attributes
					if (definingOption.type != null && definingOption.type != '') {
						// If the dropdown is selected then we need to ensure it is sorted
						var selIndex = definingOption.selectedIndex;
						var selValue = definingOption.options[selIndex].value;
	
						if (selIndex > 0) {
							previousSelected = true;						
							lastSelectedId = productPrefix;
							lastSelectedElement = definingOption;
							lastSelectedOptionNo = initIdx;
							
							// Ensure the correct option is still selected
						    for (var loop=1; loop<definingOption.options.length; loop++) {
						    	if (selValue === definingOption.options[loop].value) {
						    		definingOption.selectedIndex = loop;
									// Due to how the browser renders this on a refresh, we have encode the values back again
									definingOption.options[loop].value = definingOption.options[loop].value.replace(/&/gi,'&amp;');
						        }
						    }
						} else {
							if (initIdx==1 || previousSelected) {
								// Lets sort the current drop down 
								sortSelect(definingOption, true);
							} else {
								definingOption.length = 1; // We always leave the default option around
								definingOption.disabled="true";				
							}
							previousSelected = false; // This option has not been selected yet so preven tsubsequent options from being enabled
						}						
					}
					// Otherwise we have a set of Radio buttons for the defining attributes
					else {
						dealingWithRadioButtons = true;
					
						var selIndex = 0;
						var selValue = null;
						
						var radioChecked = false;
						
						for (i = 0; i < definingOption.childNodes.length; i++) {
							
							if (definingOption.childNodes[i].childNodes !== null) {
								
								for (j = definingOption.childNodes[i].childNodes.length - 1; j >= 0; j--) {
									
									if (definingOption.childNodes[i].childNodes[j].type == 'radio') {
										var radio = definingOption.childNodes[i].childNodes[j];
										
										if (radio.checked) {
											selIndex = j;
											selValue = radio.value;
											
											radioChecked = true;
										}
										
										if (i ==0 && j == 0 && !radioChecked) {
											// By default, check the first option
											radio.checked = true;
										}
										
									}
									
								}
								
							}
		
						}					
					}
				}
			} else {
				//debug ("Reached end of attributes");
				initIdx = maxNoOfOptions + 1;
			}		

		}

		// Save the default price details for use later
		var priceElementId = 'priceelement' + productPrefix;	
		if (document.getElementById(priceElementId)) {
			defaultPriceDetails.put(priceElementId.toUpperCase(), document.getElementById(priceElementId).innerHTML);
		}

		// Now that we have reselected all required options we need to ensure the correct price is shown using the last selected options
		// but only if a option selected
		if (previousSelected && !dealingWithRadioButtons) {
		    switchSkuSettings(document.OrderItemAddForm, lastSelectedElement, lastSelectedId, lastSelectedOptionNo, true);
		}
		

	}
	
	init = false;
}



function validateSelectedOptions (aForm, multipleProducts) {

	var maxNoOfProducts = 1;
	var maxNoOfOptions = 10;
	if (multipleProducts) {
		maxNoOfProducts = 10;
	}
	
	for (prodIdx = 1; prodIdx <= maxNoOfProducts; prodIdx++) {
		var productPrefix = "";
		if (maxNoOfProducts > 1) {
			productPrefix = "p" + prodIdx;
		}

		// Only validate if the add checkbox is present and set or noty present at all 
		var checkBoxId = productPrefix + "_selected";
		var bValidate=true;
		if (document.getElementById(checkBoxId)) {
			var includeProduct = document.getElementById(checkBoxId);
			if (!includeProduct.checked) {
				bValidate=false;
			}
		}
		
		if (bValidate) {
		for (i = 1; i <= maxNoOfOptions; i++) {
				var elementId = productPrefix + "attrValue" + (i);
				if (document.getElementById(elementId)) {
					var definingOption = document.getElementById(elementId);
					if (definingOption !== "undefined") {
						var selIndex = definingOption.selectedIndex;
						var errorText = definingOption.options[0].text + " " + definingOption.options[0].value;
						if (selIndex <= 0) {
							alert(errorText);
							return false;
						}
					}
				} else {
					i = maxNoOfOptions + 1;
				}		
			}		
		}
	}

	return true;
}

function handleSpecialChars(selValue){
	//handle encoded ampersand followed by eol
	var ampIdx=selValue.search(/\&amp;$/g);
	while(ampIdx>=0){
		selValue=insertString(selValue, ampIdx+5, "amp;");
		ampIdx=selValue.search(/\&amp;$/g);
	}
	//handle encoded ampersand followed by whitespace
	ampIdx=selValue.search(/\&amp;[\s\&]/g);
	while(ampIdx>=0){
		selValue=insertString(selValue, ampIdx+5, "amp;");
		ampIdx=selValue.search(/\&amp;[\s\&]/g);
	}						
	//handle non-ampersand special characters
	ampIdx=selValue.search(/\&[^(amp;)].*/g);
	while(ampIdx>=0){
		selValue=insertString(selValue, ampIdx+1, "amp;");
		ampIdx=selValue.search(/\&[^(amp;)]/g);
	}
	return selValue;
}
	
function insertString(origString, insertPos, insertStr) {
	var firstPart=origString.substring(0, insertPos);
	firstPart=firstPart+insertStr;
	var secondPart=origString.substring(insertPos);
	return firstPart+secondPart;
}
function getRightKeyValue(keyValue,optionNumber){
   if(keyValue=="undefined" || keyValue==null || keyValue ==""){
       return "";
   }
   var testMap = map;
   //if try to retrieve the data for the first option, we should retrieve the data from optionMap
   if(optionNumber == 1){
      testMap = optionValueMap;
   }
   var skuSettingsTmp = testMap.get(keyValue);
   if(skuSettingsTmp != "undefined" && skuSettingsTmp != null && skuSettingsTmp!=""){
       return keyValue;
   }
   var keyValue1 = keyValue.replace(/"/gi,'&#034;');
   keyValue1 = keyValue1.replace(/'/gi,"&#039;");		   
   skuSettingsTmp = testMap.get(keyValue1);
   if(skuSettingsTmp != "undefined" && skuSettingsTmp != null && skuSettingsTmp!=""){       
       return keyValue1;			           			       
   }
   var keyValue2 = handleSpecialChars(keyValue);
   skuSettingsTmp = testMap.get(keyValue2);
   if(skuSettingsTmp != "undefined" && skuSettingsTmp != null && skuSettingsTmp!=""){
       return keyValue2;			           			       
   }
   return keyValue;
}


// Define page level variables
var skuAlternativeImages = new Map();
var map = new Map();
var optionValueMap = new Map();		
var defaultPriceDetails = new Map();
var defaultMainImageSource = "";
var defaultMainImageAltText = "";
var defaultHugeImageSource = "";

// Some generic sort functions for select fields
// sort function - ascending (case-insensitive)
function sortFuncAsc(record1, record2) {
    var value1 = record1.optText.toLowerCase();
    var value2 = record2.optText.toLowerCase();
	if (value1 > value2) return(1);
    if (value1 < value2) return(-1);
    return(0);
}

// Some generic sort functions for select fields
// sort function - ascending (case-insensitive)
function sortFuncNumericAsc(record1, record2) {
    return(record1.optText - record2.optText);
}

// sort function - descending (case-insensitive)
function sortFuncDesc(record1, record2) {
    var value1 = record1.optText.toLowerCase();
    var value2 = record2.optText.toLowerCase();
    if (value1 > value2) return(-1);
    if (value1 < value2) return(1);
    return(0);
}

function sortSelect(selectToSort, ascendingOrder) {
    if (arguments.length == 1) ascendingOrder = true;    // default to ascending sort

    // copy options into an array
    // NB We skip first row as this is always 'Please select...'
    var allNumeric = true;
    var myOptions = [];
    for (var loop=1; loop<selectToSort.options.length; loop++) {
        myOptions[loop-1] = { optText:selectToSort.options[loop].text, optValue:selectToSort.options[loop].value };
        if (allNumeric) {
        	allNumeric = (!isNaN(myOptions[loop-1].optText));
        }
    }

    // sort array
    if (ascendingOrder) {
    	if (allNumeric) {
            myOptions.sort(sortFuncNumericAsc);
    	} else {
	        myOptions.sort(sortFuncAsc);
    	}
    } else {
    	if (allNumeric) {
	        myOptions.sort();
       	} else {
	        myOptions.sort(sortFuncDesc);
       	}
    }

    // copy sorted options from array back to select box
    selectToSort.options.length = 1;
    
//  SCO01/04/000014
//  Unencode "double escaped" HTML character entities in the Option texts such that &amp;quot; -> &quot; 
//  and &amp;amp; -> &amp and place them in the Select object.
    for (var loop=0; loop<myOptions.length; loop++) {
        var optObj = document.createElement('option');
        optObj.value = myOptions[loop].optValue;
        
        var beforeConvert = myOptions[loop].optText;
        //it looks like no need to deal with, the value can not contain &amp;amp; add by Michael Zhou 05/09/08
        var afterConvert = beforeConvert.replace(/&amp;/gi,"&");   	

        optObj.innerHTML = afterConvert;
        selectToSort.appendChild(optObj);	
    }
}



//*******************************************************
// Refresh product details page when colour changes
// Only used for clients that do not load colour
// as a defning option
//*******************************************************
function refreshColour (aForm, aField) {

	// Construct url to refresh to
	var selIndex = aField.selectedIndex;
	var url = aField.options[selIndex].value;

	// Now add other field values so that we dont lose selected options
	var maxNoOfOptions = 10;
	for (i = 1; i <= maxNoOfOptions; i++) {
		// Append ant selected options to the url
		var elementId = "attrValue" + (i);		
		if (document.getElementById(elementId)) {
			var definingOption = document.getElementById(elementId);
			if (definingOption != "undefined") {
				var selIndex = definingOption.selectedIndex;
				if (selIndex > 0) {
					var selValue = definingOption.options[selIndex].value;
					var selName = definingOption.name;
					url += "&" + selName + "=" + selValue;
				}
			}
		}
	}
	
	if (document.getElementById("WC_CachedProductOnlyDisplay_FormInput_quantity_In_OrderItemAddForm_1")) {
		var qty = document.getElementById("WC_CachedProductOnlyDisplay_FormInput_quantity_In_OrderItemAddForm_1");
		url += "&" + qty.name + "=" + qty.value;
	}
	
	// TODO Add the current qty and any other selected options to the request
	window.location.href = url;

}


//*******************************************************
// price updater - looks for skuSettings map array to get the latest prices


function priceUpdater (mySelectedValue) {

		var skuSettings = map.get(mySelectedValue);
	
		// if the skuSettings map is available in the source, then update the prices
		if (skuSettings !== "undefined" && skuSettings !== null && skuSettings !== "") {
	
			var displayPriceNowLabel = false;			
			if (skuSettings.getPrice().getShowWasPricePercentage() === "true" || skuSettings.getPrice().getShowWasPriceAmount() === "true") {
				displayPriceNowLabel = true;
			}
			
			// setup the price string
			var priceString = "";
			priceString += "<ul>";
			
			priceString += "<li>";
	
			// Output the latest price
			if(displayPriceNowLabel) {
				priceString += "<span class='label amount'>NOW</span>";
			} else {
				priceString += "<span class='label amount'></span>";
			}
			priceString += " <span class='amount'>" + skuSettings.getPrice().getNowPrice() + "</span></li>";
	
			//if the WAS price is available, then add it to priceString
			if (skuSettings.getPrice().getShowWasPricePercentage() === "true" || skuSettings.getPrice().getShowWasPriceAmount() === "true") {
				priceString += "<li>";			
				// was price
				priceString += "<span class='label wasprice'>Was</span><span class='wasprice'>" + skuSettings.getPrice().getWasPrice() + "</span>";
				// save percent price
				//if (skuSettings.getPrice().getShowWasPricePercentage() === "true") {
				//	priceString += "<span class='saveuptopercent label'>Save</span><span class='saveuptopercent'>" + skuSettings.getPrice().getSavingPercentage() + "%</span>";
				//}
				// save amount price
				if (skuSettings.getPrice().getShowWasPriceAmount() === "true") {
					priceString += "<span class='label saveuptoamount'>Save</span><span class='saveuptoamount'>" + skuSettings.getPrice().getSavingAmount() + "</span>";
				}
				priceString += "</li>";
			}
			priceString += "</ul>";
			
			//set priceElementId with contents of priceString
			$("#priceelement").html(priceString);
			
		} else {
			$("#priceelement").html("No price available");
		}
		
}





$(document).ready(function(){

	//*******************************************************
	// switch on/off submit button if there are no size options and it is instock
	$('div#rnconly').hide();	
	if ( $("#sizeSelectorThumbs").length == 0 ) { // then NO size options for this product
		if ( $("#lowStockQuantity").length != 0 ) { //Stock Checking is ON
			var currentStockLevel = $('.thisStockLevel').text();
			if (currentStockLevel > 0 ) {
				$("dd#quantity input").attr("disabled", false);
				$("#addToBasket").attr('src', "/wcsstore/ConsumerDirectStorefrontAssetStore/images/Master1_1/butt_add_to_basket_active.gif");
				$("#addToBasket").addClass("activeButton");
			} else {
				$("dd#quantity input").attr("disabled", true);
				$("#addToBasket").attr('src', "/wcsstore/ConsumerDirectStorefrontAssetStore/images/Master1_1/butt_out_of_stock.gif");
//$("#reserveForCollection").removeClass("activeButton");
//$("#reserveForCollection").addClass("inactiveButton");
			}
		} else { //Stock Checking is OFF
			$("dd#quantity input").attr("disabled", false);
			$("#addToBasket").attr('src', "/wcsstore/ConsumerDirectStorefrontAssetStore/images/Master1_1/butt_add_to_basket_active.gif");
			$("#addToBasket").addClass("activeButton");
		}
	}

	//*******************************************************
	// colour selector
	
	$('div#colourSelectorThumbs label').mouseover(function() {
		$(this).parent().addClass("hover");
	});
	$('div#colourSelectorThumbs label').mouseout(function() {
		$('div#colourSelectorThumbs label').parent().removeClass("hover");
	});
	$('div#colourSelectorThumbs label').click(function() {
		$('div#colourSelectorThumbs label').parent().removeClass("selected");
		$(this).parent().addClass("selected");
		//reload the page
		var url = $(this).prev().val();
		if (url != "") {
			window.location.href = url;
		}
	});

	//*******************************************************
	// size selector

	// setup the size swatch when the page loads
	$("div#sizeSelectorThumbs li").each(function (i) {
		if ( $(this).hasClass("selected") ) {
			// Update the prices for this selected size
			priceUpdater ( $(this).children("label").children("span").text() );
			$("#addToBasket").attr('src', "/wcsstore/ConsumerDirectStorefrontAssetStore/images/Master1_1/butt_add_to_basket_active.gif");
			$("#addToBasket").addClass("activeButton");

		}
	});
				
	$('div#sizeSelectorThumbs label').mouseover(function() {
		var myClassAttr = $(this).parent().attr('class');
		var isReservable = $(this).parent().hasClass("reservableStock");
		if ( myClassAttr == 'inStock' || myClassAttr == 'lowStock' || myClassAttr == 'outOfStock' || isReservable ) {
			$(this).parent().addClass("hover");
		}
	});
	$('div#sizeSelectorThumbs label').mouseout(function() {
		$('div#sizeSelectorThumbs label').parent().removeClass("hover");
	});
	$('div#sizeSelectorThumbs label').click(function() {
		//var myClassAttr = $(this).parent().attr('class').split(' ').slice();
		var isReservable = $(this).parent().hasClass("reservableStock");
		var isInstock = $(this).parent().hasClass("inStock");
		var isLowstock = $(this).parent().hasClass("lowStock");
				
		if ( isInstock || isLowstock || isReservable ) {
			$('div#sizeSelectorThumbs label').parent().removeClass("selected");
			$(this).parent().addClass("selected");
			$("#addToBasket").attr('src', "/wcsstore/ConsumerDirectStorefrontAssetStore/images/Master1_1/butt_add_to_basket_active.gif");
			$("#addToBasket").addClass("activeButton");
			$("#addToBasket").removeClass("inactiveButton");
		}
			
		// check for out of stock indicator to disable the add to basket button
		if ( $(this).parent().hasClass("outOfStock")){
			$("#addToBasket").attr('src', "/wcsstore/ConsumerDirectStorefrontAssetStore/images/Master1_1/butt_add_to_basket_inactive.gif");
			$("#addToBasket").removeClass("activeButton");
			$("#addToBasket").addClass("inactiveButton");
			$("#reserveForCollection").addClass("inactiveButton");
			$("#reserveForCollection").attr('src', "/wcsstore/ConsumerDirectStorefrontAssetStore/images/Master1_1/butt_reserve_for_collection_inactive.gif");
			$("#reserveForCollection").removeClass("activeButton");
		} else {
				// Disable button
				$("#reserveForCollection").attr('src', "/wcsstore/ConsumerDirectStorefrontAssetStore/images/Master1_1/butt_reserve_for_collection_inactive.gif");
				$("#reserveForCollection").removeClass("activeButton");
				$("#reserveForCollection").addClass("inactiveButton");
		}

		// Reservable stock button fnctionality
		if ( $(this).parent().hasClass("reservableStock")){
				// Activate button
				$(this).parent().addClass("selected");
				$("#reserveForCollection").attr('src', "/wcsstore/ConsumerDirectStorefrontAssetStore/images/Master1_1/butt_reserve_for_collection_active.gif");
				$("#reserveForCollection").removeClass("inactiveButton");
				$("#reserveForCollection").addClass("activeButton");
			}
		
		if ( $(this).parent().hasClass("reservableStock") && ($(this).parent().hasClass("outOfStock")) ){
			var size = ($(this).children().html());
			$('div#rnconly').children().html("Size "+size+" ");
			$('div#rnconly').show();
		}
		else {
			$('div#rnconly').hide();
			$('div#rnconly').children().html("Size ");
		}
		
		if ( ($(this).parent().hasClass("inStock") || $(this).parent().hasClass("lowStock")) && ($(this).parent().hasClass("inStockNotReservable")) ){
			var size = ($(this).children().html());
			$('div#atbonly').children().html("Size "+size+" ");
			$('div#atbonly').show();
		}
		else {
			$('div#atbonly').hide();
			$('div#atbonly').children().html("Size ");
		}
		
		
		
		
		
		
		
		// Now update the prices for this selected size
		priceUpdater ( $(this).children("span").text() );

		

	});
	
	
	if ( $("#sizeSelectorThumbs").length == 0 ) { // then NO size options for this product
		if ( $("#lowStockQuantity").length != 0 ) { //Stock Checking is ON
			var reservableStockLevel = $('.reservableStockExists').length;
			if (reservableStockLevel > 0 ) {
				$("dd#quantity input").attr("disabled", false);
				$("#reserveForCollection").attr('src', "/wcsstore/ConsumerDirectStorefrontAssetStore/images/Master1_1/butt_reserve_for_collection_active.gif");
				$("#reserveForCollection").addClass("activeButton");
			} else {
				var currentStockLevel = $('.thisStockLevel').text();
				// disable if out of stock for both online and reservable.
				$("dd#quantity input").attr("disabled", currentStockLevel==0 );
				$("#reserveForCollection").attr('src', "/wcsstore/ConsumerDirectStorefrontAssetStore/images/Master1_1/butt_reserve_for_collection_inactive.gif");
				$("#reserveForCollection").removeClass("activeButton");
				$("#reserveForCollection").addClass("inactiveButton");
			}
		} else { //Stock Checking is OFF
			$("dd#quantity input").attr("disabled", false);
			$("#reserveForCollection").attr('src', "/wcsstore/ConsumerDirectStorefrontAssetStore/images/Master1_1/butt_reserve_for_collection_active.gif");
			$("#reserveForCollection").removeClass("inactiveButton");
			$("#reserveForCollection").addClass("activeButton");
		}
	}
	
	

	//*******************************************************
	// Modal Window on Product Details Page

    // Function to animate opening of modal window	
    var openModal=function(hash){
		hash.w.css('opacity',1)
			.show("slow")
			.animate({opacity: '+=0'}, 4000)
			.queue(function () {
		    	$(this).jqmHide(); 
		    	$(this).dequeue();
		    });
	};

    // Function to animate closing of modal window
    var closeModal = function(hash) {
        $(".jqmOverlay").fadeOut("slow");
        var $modalWindow = $(hash.w);
	    	$modalWindow.dequeue();
			$modalWindow.fadeOut("slow", function() {
			hash.o.remove();
        });
    };

	$('.jqmWindow').jqm({overlay: 50, modal: true, trigger: false, toTop: true, onShow: openModal, onHide: closeModal});
	$('.jqmWindow').jqmShow();

});