// Based on the wonderful Mootools String.substitute
String.prototype['substitute'] = function(object, regexp, context){
	return this.replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name){
		if (match.charAt(0) == '\\') return match.slice(1);
		var dotSplit = name.split('.');
		if(dotSplit.length > 1){
			var value = object[dotSplit[0]];
			for (var i=1; i<dotSplit.length; i++) {
				if(value != undefined) value = value[dotSplit[i]];
			}
			return (value != undefined) ? value : '{' + name + '}';
		}else{
			var varSplit = name.split('var:');
			if(varSplit.length > 1 && context){
				var getter = context[varSplit[1]];
				return getter.call();
			}else{
        return (object[name] !== undefined) ? ((object[name] == null) ? "" : object[name]) : '{' + name + '}';
			}
		}
	});
};

String.prototype['getBlock'] = function(block){
	  var regexp = new RegExp("{" + block + "}([\\s\\S]*){/" + block + "}");
		var to_return = this.match(regexp);
		if(to_return){
			return this.match(regexp)[1];
		}else{
			return "";
		}
		
	};

window._edit_theme_data = { 
  edit: {
    name: "cb_edit_name",
    activity: "cb_edit_activity",
    address_1: "cb_edit_address_1",
    address_2: "cb_edit_address_2",
    city: "cb_edit_city",
    country: "cb_edit_country",
    zipcode: "cb_edit_zipcode",
    province: "cb_edit_province",
    avatar: "cb_edit_avatar",
    description: "cb_edit_description",
		phone_number: "cb_edit_phone_number",
		extra_phone_number: "cb_edit_extra_phone_number"
  }
};

// $('id').loadTheme(theme_body, user_data, service_types, services_user_data)
jQuery.fn.loadTheme = function(theme_body, user_data, service_types, services_user_data) {
  var theme_element_wrapper = $(this[0]);

	theme_body = theme_body.replace(/<#script>/g, "<\/script>");
   
  var extended_user_data = jQuery.extend(true, window._edit_theme_data, user_data);
   
  var services_theme = theme_body.getBlock("block:Services");
  var service_theme = services_theme.getBlock("block:Service");

  // Construct services string
  var services = "";
  jQuery(service_types).each(function(){
    this.service_type.username = services_user_data[this.service_type.id] != undefined ? services_user_data[this.service_type.id].username : "";
    var reg = new RegExp("^(.*)" + this.service_type.name + "(.*)$");
    if(this.service_type.username.match(reg)){
      this.service_type.url = this.service_type.username;
  	}else{
      this.service_type.url = this.service_type.url_pattern.substitute({ "username": this.service_type.username });
    }
    services += service_theme.substitute(this.service_type);
  });

  var result = theme_body.replace(/{block:Service}([\s\S]*){\/block:Service}/, services);

  result = result.replace(/{block:Services}([\s\S]*){\/block:Services}/, result.getBlock("block:Services"));
   
  // Handle Form
  result = result.replace(/{block:Form}/, "<form action='/users/" + window._user_id + "/card/contact' method='post' id='contact_form'>");
  result = result.replace(/{\/block:Form}/, "</form>");
  // End Handle Form

  var theme_edit = result.substitute(extended_user_data);
	theme_edit = processConditions(theme_edit, extended_user_data); // process Id/EndIf blocks

	theme_element_wrapper.html(theme_edit);

  var input_auth_token = $(document.createElement("input")).attr({"type": "hidden", "value": AUTH_TOKEN, "name" : "authenticity_token"});
  $("#contact_form").prepend(input_auth_token);
};

window.processConditions = function(body, data) {
	return body.replace(/{If ([a-zA-Z0-9.-_]+)}([\s\S]*){\/EndIf}/, function(matched_string, test_data, replacement){
		var test = data[test_data]
		if(test !== undefined && test != null && test != "") return replacement;
		return "";
	});
};

window.getEmailSignature = function(theme_body, user_data) {
	var not_premium_user = theme_body.getBlock("block:NotPremium");

	var result = "";
	if(user_data.premium == false){ 
		result = theme_body.replace(/{block:NotPremium}([\s\S]*){\/block:NotPremium}/, not_premium_user);
	} else {
		result = theme_body.replace(/{block:NotPremium}([\s\S]*){\/block:NotPremium}/, "");
	}

   var theme_edit = result.substitute(user_data);

   return theme_edit;
};
