/* src/dom.js (minified) */
function setLocation(url){window.location.href=url;}
function setPLocation(url,setFocus){if(setFocus){window.opener.focus();}
window.opener.location.href=url;}
function setLanguageCode(code,fromCode){var href=window.location.href;var after='',dash;if(dash=href.match(/\#(.*)$/)){href=href.replace(/\#(.*)$/,'');after=dash[0];}
if(href.match(/[?]/)){var re=/([?&]store=)[a-z0-9_]*/;if(href.match(re)){href=href.replace(re,'$1'+code);}else{href+='&store='+code;}
var re=/([?&]from_store=)[a-z0-9_]*/;if(href.match(re)){href=href.replace(re,'');}}else{href+='?store='+code;}
if(typeof(fromCode)!='undefined'){href+='&from_store='+fromCode;}
href+=after;setLocation(href);}
function formatCurrency(price,format,showPlus){precision=isNaN(format.precision=Math.abs(format.precision))?2:format.precision;requiredPrecision=isNaN(format.requiredPrecision=Math.abs(format.requiredPrecision))?2:format.requiredPrecision;precision=requiredPrecision;integerRequired=isNaN(format.integerRequired=Math.abs(format.integerRequired))?1:format.integerRequired;decimalSymbol=format.decimalSymbol==undefined?",":format.decimalSymbol;groupSymbol=format.groupSymbol==undefined?".":format.groupSymbol;groupLength=format.groupLength==undefined?3:format.groupLength;if(showPlus==undefined||showPlus==true){s=price<0?"-":(showPlus?"+":"");}else if(showPlus==false){s='';}
i=parseInt(price=Math.abs(+price||0).toFixed(precision))+"";pad=(i.length<integerRequired)?(integerRequired-i.length):0;while(pad){i='0'+i;pad--;}
j=(j=i.length)>groupLength?j%groupLength:0;re=new RegExp("(\\d{"+groupLength+"})(?=\\d)","g");r=(j?i.substr(0,j)+groupSymbol:"")+i.substr(j).replace(re,"$1"+groupSymbol)+(precision?decimalSymbol+Math.abs(price-i).toFixed(precision).replace(/-/,0).slice(2):"")
if(format.pattern.indexOf('{sign}')==-1){pattern=s+format.pattern;}else{pattern=format.pattern.replace('{sign}',s);}
return pattern.replace('%s',r).replace(/^\s\s*/,'').replace(/\s\s*$/,'');};if(!window.Mage)var Mage={};Mage.Cookies={};Mage.Cookies.expires=null;Mage.Cookies.path='/';Mage.Cookies.domain=null;Mage.Cookies.secure=false;Mage.Cookies.set=function(name,value){var argv=arguments;var argc=arguments.length;var expires=(argc>2)?argv[2]:Mage.Cookies.expires;var path=(argc>3)?argv[3]:Mage.Cookies.path;var domain=(argc>4)?argv[4]:Mage.Cookies.domain;var secure=(argc>5)?argv[5]:Mage.Cookies.secure;document.cookie=name+"="+escape(value)+
((expires==null)?"":("; expires="+expires.toGMTString()))+
((path==null)?"":("; path="+path))+
((domain==null)?"":("; domain="+domain))+
((secure==true)?"; secure":"");};Mage.Cookies.get=function(name){var arg=name+"=";var alen=arg.length;var clen=document.cookie.length;var i=0;var j=0;while(i<clen){j=i+alen;if(document.cookie.substring(i,j)==arg)
return Mage.Cookies.getCookieVal(j);i=document.cookie.indexOf(" ",i)+1;if(i==0)
break;}
return null;};Mage.Cookies.clear=function(name){if(Mage.Cookies.get(name)){document.cookie=name+"="+"; expires=Thu, 01-Jan-70 00:00:01 GMT";}};Mage.Cookies.getCookieVal=function(offset){var endstr=document.cookie.indexOf(";",offset);if(endstr==-1){endstr=document.cookie.length;}
return unescape(document.cookie.substring(offset,endstr));};Date.dayNames=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];Date.abbrDayNames=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];Date.monthNames=['January','February','March','April','May','June','July','August','September','October','November','December'];Date.abbrMonthNames=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];Date.firstDayOfWeek=1;Date.format='dd/mm/yyyy';Date.fullYearStart='20';(function(){function add(name,method){if(!Date.prototype[name]){Date.prototype[name]=method;}};add("isLeapYear",function(){var y=this.getFullYear();return(y%4==0&&y%100!=0)||y%400==0;});add("isWeekend",function(){return this.getDay()==0||this.getDay()==6;});add("isWeekDay",function(){return!this.isWeekend();});add("getDaysInMonth",function(){return[31,(this.isLeapYear()?29:28),31,30,31,30,31,31,30,31,30,31][this.getMonth()];});add("getDayName",function(abbreviated){return abbreviated?Date.abbrDayNames[this.getDay()]:Date.dayNames[this.getDay()];});add("getMonthName",function(abbreviated){return abbreviated?Date.abbrMonthNames[this.getMonth()]:Date.monthNames[this.getMonth()];});add("getDayOfYear",function(){var tmpdtm=new Date("1/1/"+this.getFullYear());return Math.floor((this.getTime()-tmpdtm.getTime())/86400000);});add("getWeekOfYear",function(){return Math.ceil(this.getDayOfYear()/7);});add("setDayOfYear",function(day){this.setMonth(0);this.setDate(day);return this;});add("addYears",function(num){this.setFullYear(this.getFullYear()+num);return this;});add("addMonths",function(num){var tmpdtm=this.getDate();this.setMonth(this.getMonth()+num);if(tmpdtm>this.getDate())
this.addDays(-this.getDate());return this;});add("addDays",function(num){this.setTime(this.getTime()+(num*86400000));return this;});add("addHours",function(num){this.setHours(this.getHours()+num);return this;});add("addMinutes",function(num){this.setMinutes(this.getMinutes()+num);return this;});add("addSeconds",function(num){this.setSeconds(this.getSeconds()+num);return this;});add("zeroTime",function(){this.setMilliseconds(0);this.setSeconds(0);this.setMinutes(0);this.setHours(0);return this;});add("asString",function(format){var r=format||Date.format;if(r.split('mm').length>1){r=r.split('mmmm').join(this.getMonthName(false)).split('mmm').join(this.getMonthName(true)).split('mm').join(_zeroPad(this.getMonth()+1))}else{r=r.split('m').join(this.getMonth()+1);}
r=r.split('yyyy').join(this.getFullYear()).split('yy').join((this.getFullYear()+'').substring(2)).split('dd').join(_zeroPad(this.getDate())).split('d').join(this.getDate());return r;});Date.fromString=function(s)
{var f=Date.format;var d=new Date('01/01/1970');if(s=='')return d;s=s.toLowerCase();var matcher='';var order=[];var r=/(dd?d?|mm?m?|yy?yy?)+([^(m|d|y)])?/g;var results;while((results=r.exec(f))!=null)
{switch(results[1]){case'd':case'dd':case'm':case'mm':case'yy':case'yyyy':matcher+='(\\d+\\d?\\d?\\d?)+';order.push(results[1].substr(0,1));break;case'mmm':matcher+='([a-z]{3})';order.push('M');break;}
if(results[2]){matcher+=results[2];}}
var dm=new RegExp(matcher);var result=s.match(dm);for(var i=0;i<order.length;i++){var res=result[i+1];switch(order[i]){case'd':d.setDate(res);break;case'm':d.setMonth(Number(res)-1);break;case'M':for(var j=0;j<Date.abbrMonthNames.length;j++){if(Date.abbrMonthNames[j].toLowerCase()==res)break;}
d.setMonth(j);break;case'y':d.setYear(res);break;}}
return d;};var _zeroPad=function(num){var s='0'+num;return s.substring(s.length-2)};})();



/* JQUERY MULTI PLUGIN js/jquery.dom.multiplugin.min.js (minified) */


/* JQUERY.PAGE.JS */

// custom jquery config / docready 
jQuery(document).ready(function($) {
													
	if ($('.date-pick').length > 0) {
	Date.firstDayOfWeek = 0;
	Date.format = 'yyyy-mm-dd';
	
	$(function()
	{
	$('.date-pick').datePicker({startDate:'2003-01-01'})
	});
	
	}
	
	/*if ($('.more-info').length > 0) {
		DD_belatedPNG.fix('.more-info')
	}
	
	if ($('.icn').length > 0) {
        DD_belatedPNG.fix('.icn')
    }

    if ($('.icn_s').length > 0) {
        DD_belatedPNG.fix('.icn_s')
    }

*/
				
	// OPEN REL EXTERNAL IN NEW WINDOW
	$('a[rel*=external]').click(function(e){
		window.open($(this).attr("href")); 
		e.preventDefault();
	});
								
	//hide non-javascript elements
	$('.accessible').hide();
	
	//show javascript only elements
	$('.jscript').show();

	
   
    /* wishlist -- fixed position needed for ie6 */

    // check if the element exists
    if ($('.wish-side-panel').length > 0) {
        $(window).scroll(function() {
            $('.wish-side-panel').css('top', $(this).scrollTop() + 121 + "px");
        });
    }



	/**************************** navigation ************************** */

	if ($('#account-listed-info').length > 0) {
		
		function accountVisible() {
		$('#header-nav li').filter('.sfHover').removeClass('sfHover');
		$(this).parent().addClass("hover");
		}
		
		function accountInvisible() {
		$(this).parent().removeClass("hover");
		}
		
		$("#account-listed-info li").hoverIntent({
			sensitivity: 3,
			interval: 120,
			over: accountVisible,
			timeout: 520,
			out: accountInvisible
		});
	}

    if ($('ul.shop-access').length > 0) {
		function accountVisible2() {
			$('#header-nav li').filter(".nav-hover").removeClass("nav-hover");
			$(this).parent().parent().addClass("active");
		}
		
		function accountInvisible2() {
			$(this).parent().parent().removeClass("active");
		}
		$("ul.shop-access").hoverIntent({
			sensitivity: 3,
			interval: 220,
			over: accountVisible2,
			timeout: 520,
			out: accountInvisible2
		});
	}

	$(".item-level-0").liveHover(function(e) {
        $(this).addClass("nav-hover");
    },
    function(e) {
        $(this).removeClass("nav-hover");
    });
	
    // testing print this div
    function printDiv(div) {
        var a = window.open('', '', 'width=450,height=400');
        a.document.open("text/html");
        a.document.write($(div).html());
        a.document.close();
        a.print();
    };

	$('.print-wish').click(function(e) {
		window.print();
		e.preventDefault();
	});


    $('.store-location').hover(function() {
        $(this).addClass("hover");
    },
    function() {
        $(this).removeClass("hover")
    });

    // Print content of div
    $('.print-test').click(function(e) {
        printDiv('.wrapper');
        e.preventDefault();

    });
	
	//Init google maps
	if ( $("#gmap-wrapper").length > 0 ) {
		var store_query = $('#NZ_location').text();
		$().numoMap({query_string: store_query, storeIcon : 'DM', iconWidth : 25, iconHeight: 34, pollyColor : 'yellow', linkClass : '', iconDirectory : BASE_URL+'skin/frontend/dm/dom002/images/googlemaps/Marker'});
	
	
	}
	
	$('#domayne-locations-all').click(function(e) {
        $('#hn_at_domayne').slideToggle();
		$(this).hide();
        e.preventDefault();
    });
	
	$('#domayne-locations-hide').click(function(e) {
        $('#hn_at_domayne').slideToggle();
		$('#domayne-locations-all').show();
        e.preventDefault();
    });

	// EQUAL HEIGHTS
    $('.store-locations-grid-list').equalHeights();
    $('.catalog-listing ol.grid-row').equalHeights();
    $('.col2-set').equalHeights();



    /**************************** WISHLIST - SIDE_PANEL ****************************/
if ( !$.browser.msie && !$.browser.version <= 8 ) {
    // TOOL TIPS
    $('#mini-search-btn').bt('Search for a product ?', {
        padding: 5,
        width: 240,
        shrinkToFit: true,
        spikeLength: 5,
        spikeGirth: 10,
        cornerRadius: 3,
        fill: 'rgba(0, 172, 202, 1)',
        strokeWidth: 1,
        strokeStyle: '#FFFFFF',
        centerPointX: .5,
        // the spike extends from center of the target edge to this point
        centerPointY: .5,
        // defined by percentage horizontal (x) and vertical (y)
        closeWhenOthersOpen: true,
        positions: ['right', 'left'],
        cssStyles: {
            color: '#FFFFFF',
            fontWeight: 'normal'
        }
    });

    $('.show-account-options').bt({
        padding: 5,
        width: 240,
        shrinkToFit: true,
        spikeLength: 5,
        spikeGirth: 10,
        cornerRadius: 3,
        fill: 'rgba(0, 172, 202, 1)',
        strokeWidth: 1,
        strokeStyle: '#FFFFFF',
        centerPointX: .5,
        // the spike extends from center of the target edge to this point
        centerPointY: .5,
        // defined by percentage horizontal (x) and vertical (y)
        closeWhenOthersOpen: true,
        positions: ['right', 'bottom', 'left', 'top'],
        cssStyles: {
            color: '#FFFFFF',
            fontWeight: 'normal'
        }
    });

    $('.wish-side-panel-count .open_wishlist').bt('Click to view items <br/> in your wishlist.', {
        padding: 5,
        width: 240,
        shrinkToFit: true,
        spikeLength: 5,
        spikeGirth: 10,
        cornerRadius: 3,
        fill: 'rgba(0, 172, 202, 1)',
        strokeWidth: 1,
        strokeStyle: '#FFFFFF',
        centerPointX: .5,
        // the spike extends from center of the target edge to this point
        centerPointY: .5,
        // defined by percentage horizontal (x) and vertical (y)
        closeWhenOthersOpen: true,
        positions: ['left', 'top', 'bottom', 'right'],
        cssStyles: {
            color: '#FFFFFF',
            fontWeight: 'normal'
        }
    });
}
// FORM VALIDATION RELATED
//$("").validate();	



// FORM VALIDATION RELATED
if ( $("#form-validate").length > 0 ) {
	var validator = $("#form-validate").bind("invalid-form.validate", function() {
		$(".form-warning").html('<span id="form-warning-msg">Your form contains ' + validator.numberOfInvalids() + ' errors, see details below.</span>');
	}).validate({
		debug: true,
		errorElement: "div",
		errorContainer: $("#warning, .form-warning"),
		errorPlacement: function(error, element) {
			error.appendTo( element.parent() );
		},
		success: function(label) {
			label.remove();
		},
/*		rules: {
			telephone: {
				required:true,
				telephone: "Please enter a valid telephone number",
				number:true	
			}
		},
		messages: {
			telephone: {
				required: " ",
				phone: "123456"	
			},
			email: {
				required: " ",
				email: "Please enter a valid email address"
			}
		},*/
		submitHandler: function(form) {
			$("button").attr('disabled', 'disabled');
			form.submit();
		}
	});
}

	
    /****************************MINI SEARCH FORM****************************/

    //uses autocomplete plugin - http://www.pengoworks.com/workshop/jquery/autocomplete.htm
    //based on http://dyve.net/jquery/?autocomplete
    /*$("#search").autocomplete("/catalogsearch/ajax/suggest/", {
        //autoFill: 		false;
        //inputClass: 		"ac_input",
        resultsClass: "search_autocomplete",
        //loadingClass: 	"ac_loading",
        lineSeparator: "\n",
        //delay:			400,
        //cacheLength:		1,
        maxItemsToShow: 10,
        minChars: 2,
        formatItem: function(row, position, itemcount) {
            return '<span class="amount">' + row[1] + '</span>' + row[0];
        }
    });*/
    $("#search_mini_form").submit(function() {
        var value=$('#search').val();
		if (value == 'Search for product...') {
            $("#search").fadeOut('fast').fadeIn('slow');
            return false;
        } else if(value.length < 3){
			alert('Please enter at least 3 characters');
			return false;
		}else return true;
    });

    // REMOVE BACK-TO-TOP ALL PAGES
    removeBackToTop();

    function removeBackToTop() {
        if ($('.wrapper').height() < $(window).height()) {
            $('.back-to-top').css('display', 'none')
        }
    }

    //ONBLUR/ONFOCUS for input text and textarea fields
    function init_swap_text_boxes() {
        var swap_text_boxes = Array();
        $('input[type=text][value].swaptextbox').each(function() {
            swap_text_boxes[$(this).attr('id')] = $(this).attr('value');
        });
        $('input[type=text][value].swaptextbox').bind('focus',
        function() {
            if ($(this).val() == swap_text_boxes[$(this).attr('id')]) $(this).val('');
        });
        $('input[type=text][value].swaptextbox').bind('blur',
        function() {
            if ($(this).val() == '') $(this).val(swap_text_boxes[$(this).attr('id')]);
        });
        var swap_text_areas = Array();
        $('textarea[value].swaptextbox').each(function() {
            swap_text_areas[$(this).attr('id')] = $(this).attr('value');
        });
        $('textarea[value].swaptextbox').bind('focus',
        function() {
            if ($(this).val() == swap_text_areas[$(this).attr('id')]) $(this).val('');
        });
        $('textarea[value].swaptextbox').bind('blur',
        function() {
            if ($(this).val() == '') $(this).val(swap_text_areas[$(this).attr('id')]);
        });
    }
    init_swap_text_boxes();

    /****************************  LOGIN DIV  ***************************

    $(function(e) {
        $('li.login-anchor a, a.login-to-account').live('click',
        function(e) {
            $('#login-div').modal({
                closeClass: "close-login",
                overlayClose: true
            });
            e.preventDefault();
        });
    });
	
	*/

    $(function(e) {
        $('a.install-login').live('click',
        function(e) {
            $('#login-div').modal({
                closeClass: "close-login",
                overlayClose: true
            });
            e.preventDefault();
        });
    });


    //add Hover class to listed items
    /* ***************************  PROMO PAGE Hovers  ***************************	*/

    $('.listing-type-promo-grid li.item, .wish-side-panel-count').hover(function() {
        $(this).addClass("hover");
    },
    function() {
        $(this).removeClass("hover")
    });

    // CATALOG PRODUCT HOVER
    $('.listing-type-grid.catalog-listing li.item, .grouped-grid li.item').hover(function() {
        $(this).addClass("hover");
        //$(this).find("div.box").addClass("hover");
        $(this).find(".wish-icon").show();
    },
    function() {
        $(this).removeClass("hover");
        //$(this).find("div.box").removeClass("hover");
        $(this).find(".wish-icon").hide();
    });

    /****************************OPEN MY WISHLIST MODAL WNDOW****************************/

    /************************MESSAGES****************************/

    function bubbleDisplay(message, type) {
        if (message) {
            if (message.length > 3000) message = 'Possible error, please refresh the page.';
            $.jGrowl('', {

                header: '<div class="message"><span style="">' + message + '</span></div>',
                theme: 'balloon',
                sticky: function() {
                    if (type == 'error') return true;
                    else return false;
                },
                life: 5000,
                check: 5000,
                speed: function() {
                    if (jQuery.browser.msie) {
                        return 'slow';
                    } else return '0';
                }
            });
        }
    }

    /******************************AJAX******************************/

    //globals
    var PROCESSING_IMG = '<img class="processing" src="' + PROCESSING_IMG_SRC + '" alt="" />';
    var PROCESSING_LIST_IMG = '<img class="processing" src="' + SKIN_URL + '/images/icons/ajax-loader.new.gif'; + '" alt="" />';

    //for every ajax error that occurs
    function ajaxError(clicked_element) {
        bubbleDisplay('An error occured! Please refresh the page and try again.', 'error');
        $('img.processing').remove();
        clicked_element.show();
    }


    /**********************AJAX WISHLIST EVENTS**********************/

    /**add**/

    /*
	
	//TURNING OFF WISHLIST
	
	//remove from wishlist - on listed page
    $('.item a.wish.selected').live("click",
    function(e) {
        if (LOGGED_IN) {
            wishAjaxRemove($(this), 'wishlist-remove-product-view');
        }

        e.preventDefault();
    });

    //add to wishlist - on listed page
    $('.item a.wish.unselected').live("click",
    function(e) {
        if (LOGGED_IN) {
            wishAjaxAdd($(this), 'wishlist-add-product-view');
        } else {
            $('#login-div').modal({
                closeClass: "close-login",
                overlayClose: true
            });

        }
        e.preventDefault();
    });
	
	//remove from wishlist - on product view page
    $('.product-shop a.wish.selected').live("click",
    function(e) {
        if (LOGGED_IN) {
            wishAjaxRemove($(this), 'wishlist-remove-product-view');
        }

        e.preventDefault();
    });

    //add to wishlist - on product view page
    $('.product-shop a.wish.unselected').live("click",
    function(e) {
        if (LOGGED_IN) {
            wishAjaxAdd($(this), 'wishlist-add-product-view');
        } else {
            $('#login-div').modal({
                closeClass: "close-login",
                overlayClose: true
            });

        }
        e.preventDefault();
    });

	//remove from wishlist - on customer wishlist page
    $('.customer-wishlist a.link-remove').live("click",
    function(e) {
        if (LOGGED_IN) {
            wishAjaxRemove($(this), 'wishlist-remove-modal-view');
        }
        e.preventDefault();
    });
*/
    /**
	
	save comments
	
	**/
    
	
	
	//add comment toggle
    $('a.comment-toggle').live('click',
    function(e) {
        $(this).parent().find(".wish-comments").toggle();
		$(this).next('a.wish-comment-save').toggle();
		$(this).parent().find('.wish-saved-comment').toggle();

        if ($(this).text() == 'Add / Edit Comment') {
            $(this).text('Cancel');			
        } else {
            $(this).text('Add / Edit Comment');
        }
        e.preventDefault();
    });

    //save comments
    $('a.wish-comment-save').live('click',
    function(e) {
        
		$('#updatedFavouritesForm').submit();
		/*
		
		//TURNING OFF WISHLIST
		
		$(this).prev('a.comment-toggle').click();
        wishAjaxSave($(this));
        var comment_text = $(this).parent().find('.wish-comments .wish-comment-field').val();
        $(this).parent().find('.wish-saved-comment').text(comment_text);
        return false;
        e.preventDefault();*/
    });

    /********************AJAX WISHIST FUNCTIONS*******************
	
	wishAjaxRemove
	
	*/

   /*
   
   //TURNING OFF WISHLIST
   
    var PROCESSING_AJAX_WISHES = 0;
    var overlay_element = $("<div class='ajax-overlay'></div>");
    var tooltip_attribute = "bt-xtitle";
   // $('.item .wish-icon').toggle();

    //before calling any wishlist related ajax
    function wishAjaxPrepare(clicked_element, overlay_element, AJAX_PROCESSING_IMG) {
        overlay_element.append(AJAX_PROCESSING_IMG);
        PROCESSING_AJAX_WISHES++;
    }

    //for every wishlist related ajax error that occurs
    function wishAjaxError(clicked_element) {
        ajaxError(clicked_element);
        PROCESSING_AJAX_WISHES--;
    }

    //toggle between adding to wishlsit and removing
    function wishToggle(clicked_element, clicked_id, toggle_to) {
        if (toggle_to == 'add') {
            if (clicked_id) var new_href = clicked_element.attr('href').replace(/remove\/item\/\d+/, "addajax/product") + clicked_id + '/';
            var wish_span_text = "Add to wishlist";
        } else {
            if (clicked_id) var new_href = clicked_element.attr('href').replace(/add\/item\/\d+/, "removeajax/product") + clicked_id + '/';
            var wish_span_text = "Remove from wishlist";
        }
        if (new_href) clicked_element.attr({
            'href': new_href
        });
        
		clicked_element.toggleClass('selected').toggleClass('unselected').attr(tooltip_attribute, wish_span_text).find("span.wish-txt").text(wish_span_text);
        
		//clicked_element.find(".wish-visible-icon").attr("src", SKIN_URL + icon_image).show();
    }

    //for every wishlist related ajax call that is successful
    function wishAjaxSuccess(clicked_element, click_type) {

        if (click_type == 'wishlist-remove-modal-view') {
            var clicked_id = clicked_element.attr('id').replace('wish_modal_', '');
            clicked_element.parent().parent().fadeOut('slow').remove();
            wishToggle($("#wish_product_" + clicked_id + ".wish-selected"), clicked_id, 'add');
        } else {
            var clicked_id = clicked_element.attr('id').replace('wish_product_', '');
            if (click_type == 'wishlist-add-grid-view') {
                wishToggle(clicked_element, clicked_id, 'remove');
            } else if (click_type == 'wishlist-remove-grid-view') {
                wishToggle(clicked_element, clicked_id, 'add');
            } else if (click_type == 'wishlist-add-product-view') {
                wishToggle(clicked_element, clicked_id, 'remove');
            } else if (click_type == 'wishlist-remove-product-view') {
                wishToggle(clicked_element, clicked_id, 'add');
            } else if (click_type == 'wishlist-remove-product-list') {
                wishToggle(clicked_element, clicked_id, 'remove');
			}
					
        }

        $('img.processing').remove();
        $(".wish-side-panel").show();

        PROCESSING_AJAX_WISHES--;
        if (PROCESSING_AJAX_WISHES == 0) wishAjaxUpdate();
    }

    //update the wishlist via ajax
    function wishAjaxUpdate() {
        $('.wishlist-li').load(BASE_URL + 'ajaxcart/index/myfavouritescount', '',
        function() {
            $('.sidebar_progress_bar').remove()
        });

        $('.wish-side-panel-count').load(BASE_URL + 'ajaxcart/index/myfavouritescount');

    }

    //gets the remove wishlist url from magento via ajax
    function wishAjaxGetReplacement(clicked_element, href) {
        $.get(href,
        function(new_href) {
            clicked_element.attr({
                'href': new_href
            });
        });
    }

    //add to wishlist
    function wishAjaxAdd(clicked_element, click_type) {

        if (click_type == 'wishlist-add-grid-view') var WISH_PROCESSING_IMG = PROCESSING_LIST_IMG;

        else var WISH_PROCESSING_IMG = PROCESSING_IMG;

        var ajaxhref = clicked_element.attr('href').replace(/\/add\//, "/addajax/");

        $.ajax({
            url: ajaxhref,
            beforeSend: function() {
                if (click_type == 'wishlist-add-product-view') {
                    wishAjaxPrepare(clicked_element, overlay_element, WISH_PROCESSING_IMG);
                    clicked_element.parent().animate({
                        opacity: .2
                    },
                    700);
                    // clicked_element.parent().parent().append(overlay_element.text('Adding item to view wishlist').append(WISH_PROCESSING_IMG));
                	bubbleDisplay('Item being added to your to wishlist');
				} else {
                    wishAjaxPrepare(clicked_element, overlay_element, WISH_PROCESSING_IMG);
                    clicked_element.parent().animate({
                        opacity: .2
                    },
                    700);
                    // clicked_element.parent().parent().append(overlay_element.text('Adding item to wishlist').append(WISH_PROCESSING_IMG));
                	bubbleDisplay('Item being added to your to wishlist');
				}
            },
            error: function() {
                wishAjaxError(clicked_element)
            },
            success: function(message) {
                wishAjaxSuccess(clicked_element, click_type);
                bubbleDisplay(message);
                overlay_element.remove();
                clicked_element.parent().animate({
                    opacity: 1
                },
                700);
            },
            complete: function(XMLHttpRequest, textStatus) {
                if (textStatus == 'success') {
                    var replacehref = ajaxhref.replace(/\/add[a-zA-Z]+\//, "/removeajaxurl/");
                    if (replacehref) wishAjaxGetReplacement(clicked_element, replacehref);
                }
            }
        });
    }

    //remove from wishlist (from both icons and favourites table)
    function wishAjaxRemove(clicked_element, click_type) {

        if (click_type == 'wishlist-remove-grid-view') var WISH_PROCESSING_IMG = PROCESSING_LIST_IMG;
        else WISH_PROCESSING_IMG = PROCESSING_IMG;

        var ajaxhref = clicked_element.attr('href').replace(/\/remove\//, "/removeajax/");

        $.ajax({
            url: ajaxhref,
            beforeSend: function() {
                if (click_type == 'wishlist-remove-product-view') {
                    wishAjaxPrepare(clicked_element, overlay_element, WISH_PROCESSING_IMG);
                    clicked_element.parent().animate({
                        opacity: .3
                    },
                    700);
                    clicked_element.parent().parent().append(overlay_element.text('Removing item from wishlist - view').append(WISH_PROCESSING_IMG));
               
				    bubbleDisplay('Item being removed from your to wishlist');
			   
			   }  else if (click_type == 'wishlist-remove-modal-view') {
                    wishAjaxPrepare(clicked_element, overlay_element, WISH_PROCESSING_IMG);
                    clicked_element.hide();
                    //clicked_element.parent().append(overlay_element.text('Removing item from wishlist - modal view').append(WISH_PROCESSING_IMG));
                	bubbleDisplay('Item being removed from your to wishlist');
				} else {
                    wishAjaxPrepare(clicked_element, overlay_element, WISH_PROCESSING_IMG);
                    clicked_element.parent().animate({
                        opacity: .3
                    },
                    700);
                    //clicked_element.parent().parent().append(overlay_element.text('Removing item from wishlist -- defaulted').append(WISH_PROCESSING_IMG));
                	bubbleDisplay('Item being removed from your to wishlist');
				}
            },
            error: function() {
                wishAjaxError(clicked_element)
            },
            success: function(message) {
                wishAjaxSuccess(clicked_element, click_type);
                bubbleDisplay(message);
                overlay_element.remove();
                if (click_type == 'wishlist-remove-modal-view') clicked_element.parent().parent().animate({
                    opacity: 1
                },
                1400).remove();
                else clicked_element.parent().animate({
                    opacity: 1
                },
                700);
            }
        });
    }

    //save wishlist form info
    function wishAjaxSave(clicked_element) {
        var href = $('#updatedFavouritesForm').attr('action');
        var serialized_form = $('#updatedFavouritesForm').serialize();
        $.ajax({
            url: href,
            type: "POST",
            data: serialized_form,
            //beforeSend: function(){wishAjaxPrepare(clicked_element, PROCESSING_IMG)},
            error: function() {
                wishAjaxError(clicked_element)
            },
            success: function() {
                wishAjaxSuccess(clicked_element);
                return true;
            }
        });
        return false;
    }*/

});

//add to wishlist - on product grid
/*$('.listing-type-grid a.wish, .grouped-grid a.wish').live("click",
    function(e) {
        if (LOGGED_IN) {
            wishAjaxAdd($(this), 'wishlist-add-grid-view');
        } else {
            $('#login-div').modal({
                closeClass: "close-login",
                overlayClose: true
            });
        }
        return false;
    });*/

/**remove**/

//remove from wishlist - on product grid
/* $('a.wish.selected').live("click",
    function(e) {
        if (LOGGED_IN) {
            wishAjaxRemove($(this), 'wishlist-remove-grid-view');
			
			
			
        } else {
            $('#login-div').modal({
                closeClass: "close-login",
                overlayClose: true
            });
            e.preventDefault();
        }

        e.preventDefault();
    });*/

