// Replaces all instances of the given substring.
String.prototype.replaceAll = function( 
	strTarget, // The substring you want to replace
	strSubString // The string you want to replace in.
	){
	var strText = this;
	var intIndexOfMatch = strText.indexOf( strTarget );
	 
	// Keep looping while an instance of the target string
	// still exists in the string.
	while (intIndexOfMatch != -1){
		// Relace out the current instance.
		strText = strText.replace( strTarget, strSubString )
		 
		// Get the index of any next matching substring.
		intIndexOfMatch = strText.indexOf( strTarget );
	}
	 
	// Return the updated string with ALL the target strings
	// replaced out with the new substring.
	return( strText );
}


/*
 * TextLimit - jQuery plugin for counting and limiting characters for input and textarea fields
 * 
 * pass '-1' as speed if you don't want slow char deletion effect. (don't just put 0)
 * Example: jQuery("Textarea").textlimit('span.counter',256)
 *
 * $Version: 2007.10.24 +r1
 * Copyright (c) 2007 Yair Even-Or
 * vsync.design@gmail.com
 */
jQuery.fn.textlimit=function(counter_el, thelimit, speed) {
	var charDelSpeed = speed || 15;
	var toggleCharDel = speed != -1;
	var toggleTrim = true;
	
	var that = this[0];
	updateCounter();
	
	function updateCounter(){
		jQuery(counter_el).text(thelimit - that.value.length);
	};
	
	this.keypress (function(e){ if( this.value.length >= thelimit && e.charCode != '0' ) e.preventDefault() })
	.keyup (function(e){
		updateCounter();
		if( this.value.length >= thelimit && toggleTrim ){
			if(toggleCharDel){
				// first, trim the text a bit so the char trimming won't take forever
				that.value = that.value.substr(0,thelimit+100);
				var init = setInterval
					( 
						function(){ 
							if( that.value.length <= thelimit){ init = clearInterval(init); updateCounter() }
							else{ that.value = that.value.substring(0,that.value.length-1); jQuery(counter_el).text('trimming...  '+(thelimit - that.value.length)); };
						} ,charDelSpeed 
					);
			}
			else this.value = that.value.substr(0,thelimit);
		}
	});
	
};

function Get_Counties(infield,outfield,selectname,preselected) {
	var usefunction = "Get_Counties";
	var incountry = $('#' + infield).val();
	
	var workdrp = '<select name="shop_county" id="shop_county" class="input300" onChange="Get_Towns(\'shop_county\',\'townsdiv\',\'shop_town\',\'\')"><option value="">Loading...</option></select>';
	$('#' + outfield).html(workdrp);
	// post start
	
	$.post("market_ajax.php", 
	{ 	
		usefunction: usefunction, 
		preselected: preselected,
		incountry: incountry
	},
	function(data){ 
		//alert(data); 
		if(data == "") {
			var printfield = '<input type="text" id="' + selectname + '" name="' + selectname + '" value="' + selectname + '" class="input300" />';
			$('#' + outfield).html(printfield);
			
			var printfield2 = '<input type="text" id="shop_town" name="shop_town" value="shop_town" class="input300" />';
			$('#townsdiv').html(printfield2);
			
		} else {
		$('#' + selectname).html(data);
		}
	}
	);
	setaddress();
	// post end
	
} 


function Get_Towns(infield,outfield,selectname,preselected) {
	var usefunction = "Get_Towns";
	var incounty = $('#' + infield).val();
	
	var workdrp = '<select name="shop_town" id="shop_town" class="input300" onChange="Get_Post(\'shop_town\',\'shop_postcode\',\'\')"><option value="">Loading...</option></select>';
	$('#' + outfield).html(workdrp);
	
	// post start
	
	$.post("market_ajax.php", 
	{ 	
		usefunction: usefunction, 
		preselected: preselected,
		incounty: incounty
	},
	function(data){ 
		//alert(data); 
		if(data == "") {
			var printfield = '<input type="text" id="' + selectname + '" name="' + selectname + '" value="' + selectname + '" class="input300" />';
			$('#' + outfield).html(printfield);
		} else {
		$('#' + selectname).html(data);
		}
		setaddress();
	}
	);
	
	// post end
}

function Get_Towns_pre(infield,outfield,selectname,preselected) {
	var usefunction = "Get_Towns";
	var incounty = infield;
	
	var workdrp = '<select name="shop_town" id="shop_town" class="input300" onChange="Get_Post(\'shop_town\',\'shop_postcode\',\'\')"><option value="">Loading...</option></select>';
	$('#' + outfield).html(workdrp);
	
	// post start
	
	$.post("market_ajax.php", 
	{ 	
		usefunction: usefunction, 
		preselected: preselected,
		incounty: incounty
	},
	function(data){ 
		//alert(data); 
		if(data == "") {
			var printfield = '<input type="text" id="' + selectname + '" name="' + selectname + '" value="' + selectname + '" class="input300" />';
			$('#' + outfield).html(printfield);
		} else {
		$('#' + selectname).html(data);
		}
		setaddress();
	}
	);
	
	// post end
}

function Get_Post(infield,selectname,preselected) {
	var usefunction = "Get_Post";
	var intown = $('#' + infield).val();
	
	// post start
	
	$.post("market_ajax.php", 
	{ 	
		usefunction: usefunction, 
		preselected: preselected,
		intown: intown
	},
	function(data){ 
		//alert(data); 
		$('#' + selectname).val(data);
		setaddress();
	}
	);
	
	// post end
}

function setaddress() {
	var shop_address = $('#shop_address').val();
	var shop_town = $('#shop_town').val();
	var shop_county = $('#shop_county').val();
	var shop_country = $('#shop_country').val();
	var shop_postcode = $('#shop_postcode').val();
	
	var address = shop_address + " " + shop_town + " " + shop_county + " " + shop_country + " " + shop_postcode;
	
	$('#upaddress').val(address);
	
}

function ShowHideDiv(divname) {
	var curstate = document.getElementById(divname).style.display;
	//alert(curstate);
	if(curstate == "none") {
		document.getElementById(divname).style.display = "";
	} else {
		document.getElementById(divname).style.display = "none";
	}
}

$(function(){ 

	$('#alert').dialog({
		autoOpen: false,
		width: 350, 
		height: 100,
		zIndex: 4000,
		resizable: false,
		modal: true
	});
	
	$('#logondiv').dialog({
	autoOpen: false,
	width: 340, 
	height: 320,
	zIndex: 1000,
	resizable: false,
	modal: true,
	buttons: {
		"Login": function() { 
			//$(this).dialog("close");
			
			// post start
			
			var logfunc = "dologon";
			var logemail = $('#logemail').val();
			var logpass = $('#logpass').val();
			
			$.post("logonexecute.php", 
			{ 	
				logfunc: logfunc, 
				logemail: logemail,
				logpass: logpass
			},
			function(data){ 
				//alert(data); 
				
				if(data == "false") {
					$('#logonmessage').html('Your logon details could not be verified.');
				} else {
					$('#logonmessage').html('Welcome Back');
					
					var goloc = document.URL;
					
					//window.location = goloc;
					$('#logondiv').dialog("close");
				}
				
			}
			);
			
			// post end
			
		}
		,
		"Send Reminder": function() { 
			//$(this).dialog("close");
			
			// post start
			
			var logfunc = "reminder";
			var logemail = $('#logemail').val();
			
			$.post("logonexecute.php", 
			{ 	
				logfunc: logfunc, 
				logemail: logemail
			},
			function(data){ 
				//alert(data); 
				
				if(data == "false") {
					$('#logonmessage').html('E-mail address not found.');
				} else {
					$('#logonmessage').html('Password sent to registered e-mail address.');
				}
				
			}
			);
			
			// post end
			
		}
		, 
		"Close": function() { 
			$(this).dialog("close"); 
		} 
	}
	});
	
	$('#reguserdiv').dialog({
	autoOpen: false,
	width: 250, 
	height: 380,
	zIndex: 1000,
	resizable: false,
	modal: true,
	buttons: {
		"Register": function() { 
			//
			
			//user_screenname,user_email,user_emailconfirm,user_password,user_passwordconfirm
			
			// showalert('regusererr')
			
			var showrerr = 0;
			
			var user_screenname = $('#user_screenname').val();
			var user_email = $('#user_email').val();
			var user_emailconfirm = $('#user_emailconfirm').val();
			var user_password = $('#user_password').val();
			var user_passwordconfirm = $('#user_passwordconfirm').val();
			
			if(user_screenname == "") { showrerr = 1; }
			
			if(user_email == "") { showrerr = 1; }
			if(user_emailconfirm == "") { showrerr = 1; }
			if(user_email !== user_emailconfirm) { showrerr = 1; }
			
			if(user_password == "") { showrerr = 1; }
			if(user_passwordconfirm == "") { showrerr = 1; }
			if(user_password !== user_passwordconfirm) { showrerr = 1; }
			
			if(showrerr == 1) {
				showalert('regusererr');
			} else {
				// pststart
				
				$.post("reg_usersave.php", 
				{ 	
					user_screenname: user_screenname,
					user_email: user_email,
					user_password: user_password
				},
				function(data){ 
					//alert(data); 
					
					// emexists regtrue
					
					if(data == "true") {
						showalert('regtrue');
						$('#reguserdiv').dialog("close");
					} else {
						showalert('emexists');
					}
					
				}
				);
				
				// pstend
			}
			
		}
		, 
		"Cancel": function() { 
			$(this).dialog("close"); 
		} 
	}
	});

});

function reguser() {
	var agourl = "reg_user.php";
		
		$("#reguserdiv").load(agourl);
		
		$('#reguserdiv').dialog('option', 'title', 'Register as a User');
		$('#reguserdiv').dialog('open');
}


function logonuser() {
	var agourl = "logon.php";
		
		$("#logondiv").load(agourl);
		
		$('#logondiv').dialog('option', 'title', 'User Login');
		$('#logondiv').dialog('open');
}

function addshop() {
	index = document.cookie.indexOf("marketuser");
	
	if(index != -1) { 
		window.location = "add_a_shop.php";
	} else {
		logonuser();
	}
	
}

function showalert(type) {
	if(type == "logerror") {
		var erm = '<div style="background: url(\'images/alert.png\') 0px 0px no-repeat; height: 100px;"><div style=" padding: 15px 0px 0px 80px;">You need to be logged in to use this function.<\/div><\/div>';
	}
	if(type == "comadded") {
		var erm = '<div style="background: url(\'images/alert.png\') 0px 0px no-repeat; height: 100px;"><div style=" padding: 15px 0px 0px 80px;">Your comment has been added.<\/div><\/div>';
	}
	if(type == "regusererr") {
		var erm = '<div style="background: url(\'images/alert.png\') 0px 0px no-repeat; height: 100px;"><div style=" padding: 15px 0px 0px 80px;">Missing registration information. Or your e-mail\/passwords don\'t match.<\/div><\/div>';
	}
	if(type == "emexists") {
		var erm = '<div style="background: url(\'images/alert.png\') 0px 0px no-repeat; height: 100px;"><div style=" padding: 15px 0px 0px 80px;">Supplied e-mail has been registered before.<\/div><\/div>';
	}
	if(type == "regtrue") {
		var erm = '<div style="background: url(\'images/alert.png\') 0px 0px no-repeat; height: 100px;"><div style=" padding: 15px 0px 0px 80px;">Thank You. You are now registered and can login.<\/div><\/div>';
	}
	if(type == "regshoptrue") {
		var erm = '<div style="background: url(\'images/alert.png\') 0px 0px no-repeat; height: 100px;"><div style=" padding: 15px 0px 0px 80px;">Thank You. We will activate your account once your details have been verified.<\/div><\/div>';
	}
	if(type == "wishadded") {
		var erm = '<div style="background: url(\'images/alert.png\') 0px 0px no-repeat; height: 100px;"><div style=" padding: 15px 0px 0px 80px;">Product added to your wishlist.<\/div><\/div>';
	}
	
	$('#alert').html(erm);
	$('#alert').dialog('option', 'title', 'Alert');
	$('#alert').dialog('open');
}

function showeditbuttons() {
	index = document.cookie.indexOf("marketuser");
	
	if(index != -1) { 
		
	} else {
		logonuser();
	}
}

function working_show(title,message,timer) {
	
	$.popup.show(title, message);
	
	if(timer != 0) {
		setTimeout(function() { 
			$('#popup_bg').hide(); 
			$('#popup').hide(); 
		}, timer);
	}
}

jQuery.popup = {
  
  /**
   * Show a pop-up with given title and message.
   *
   * @param title : popup title
   * @param message : popup content message
   * @param options : optional settings, can contain following params:
   *          convertNLtoBR : if true, will convert new lines (\n) to <br/> in message
   *          postDOM : function to call after creating popup elements, just before showing it (only called once)
   *          simpleAlert : if true, will use javascript's standard alert() function (auto-used if client = iPhone/iPod)
   *          main_class : class names to be added on main popup <div> tag
   *          xxx_id : id to use for popup elements, shouldn't need to modify
   * @return jQuery
   */
  show: function(title, message, options) {
  
    // define defaults and override with options if available
    settings = jQuery.extend({
      convertNLtoBR: true, 
      postDOM: function(){}, 
      simpleAlert: false, 
      main_class: "", 
      main_id: "popup", 
      bg_id: "popup_bg", 
      title_id: "popup_title", 
      msg_id: "popup_message", 
      close_id: "popup_close" 
      }, options);
  
    if(!this.initialized) {
      // inject needed elements in DOM
      domElements = '<div id="'+settings.bg_id+'"></div>';
      domElements += '<div id="'+settings.main_id+'" class="'+settings.main_class+'">';
      domElements += '<span id="'+settings.title_id+'"></span><a id="'+settings.close_id+'"> </a>';
      domElements += '<div id="'+settings.msg_id+'"></div>';
      domElements += '</div>';
      jQuery('body').append(domElements);

      // call given method after DOM has been altered (maybe user wants to attach to elements, or whatever)
      settings.postDOM();
      
      // setup event handlers
      // popup close by outer click
      jQuery('#'+settings.bg_id).click( function(){hidePopup();} );
      jQuery('#'+settings.close_id).click( function(){hidePopup();} );
    
      this.initialized = true;
    }
    
    if(!isIPhone() && !settings.simpleAlert) {
      // convert \n into <br/> if asked to (only in message param)
      if(settings.convertNLtoBR) {
        message = message.replace(/\n/g, "<br/>");
      }
      // prepare popup content
      jQuery('#'+settings.title_id).html(title);
      jQuery('#'+settings.msg_id).html(message);
      // display.. tadaaa!
      showPopup();
    } else {
      alert(message);
    }
  
    /*
     *
     * private functions (they're included right INTO the main show function)
     *
     */
  
    // show popup
    function showPopup() {
      // loads popup only if it is disabled
      //if(!this.showing) {
        centerPopup();
        jQuery('#'+settings.bg_id).css({"opacity": "0.6"});
        jQuery('#'+settings.bg_id).show();
        jQuery('#'+settings.main_id).show();
        this.showing = true;
      //}
    }
    
    // hide popup
    function hidePopup() {
      // disables popup only if it is enabled
      if(this.showing) {
        jQuery('#'+settings.bg_id).fadeOut("normal");
        jQuery('#'+settings.main_id).fadeOut("normal");
        this.showing = false;
      }
    }
    
    // center popup in viewport
    function centerPopup() {
      // get viewport dimensions
      var cWidth = document.documentElement.clientWidth;
      var cHeight = document.documentElement.clientHeight;
      var popupHeight = jQuery('#'+settings.main_id).height();
      var popupWidth = jQuery('#'+settings.main_id).width();
      // positionning
      jQuery('#'+settings.main_id).css({
        "top": cHeight/2-popupHeight/2, 
        "left": cWidth/2-popupWidth/2
      });
      // IE6 
      jQuery(settings.bg_id).css({"height": cHeight});
    }
    
    // detects if browser is iPhone/iPod Safari
    function isIPhone() {
    	if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
    	   return true;
      }
      return false;
    }
    
    return jQuery;
  
  }, // end show function
  
  // jQuery.fn.name = function(..){...} => call $('selector').name
  // jQuery.name = function(..){...} => call $.name
  // jQuery.namespace = {name: function(..){...}, .. } => call $.namespace.name
  // inside plugin: use jQuery, not $ alias which might not exist
  
  // popup ready or not
  initialized: false,
  
  // false = disabled, true = enabled
  showing: false

};  // ';' required or will break if compressed

/*
 * Addthis 0.1
 * (c)2009 Brent Wong
 * 
 * Usage:
 *  $.addthis();
 *   -or-
 *  $.addthis('username');
 *  where username is your AddThis username. Useful for tracking statistics
*/
(function($){
	$.addthis = function(code){

		function init(){
			try{
				// determine whether to include the normal or SSL version
				var addthisurl = (location.href.indexOf('https') == 0 ? 'https://' : 'http://') + 's7.addthis.com/js/250/addthis_widget.js?pub=' + code;

				// include the script
				$.getScript(addthisurl, function(){
					$('a.addthis').append('<img src="http://s7.addthis.com/static/btn/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/>').attr('href', 'http://www.addthis.com/bookmark.php?v=250').mouseover(
						function(){
							return addthis_open(this, '', '[URL]', '[TITLE]');
						}).mouseout(
						function(){
							addthis_close();
						}).click(
						function(){
							return addthis_sendto();
						});
				});
			} catch(err) {
				// log any failure
				console.log('Failed to load AddThis Script:' + err);
			}
		}

		init();
	}
})(jQuery);

