String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

/* integrate this into MWD_BASE */
function form_default_focus_handler(){
	
	$$('input[type="text"], textarea').each(function(el){
		default_value = el.getAttribute('default')
		if(default_value){
			el.observe('focus', function(e){if(e.element().value == e.element().getAttribute('default')){ e.element().value = '' } }) 
			el.observe('blur', function(e){if(e.element().value.trim() == ""){ e.element().value = e.element().getAttribute('default') } }) 
			if(el.value.trim() == ""){ el.value = default_value }
		}
	})
}
document.observe('dom:loaded', form_default_focus_handler)
/* integrate this into MWD_BASE */



Array.prototype.unique = function () {
    var hash = new Object();
    for (j = 0; j < this.length; j++) {
        hash[this[j]] = true
    }
    var array = new Array();
    for (value in hash) {
        array.push(value)
    };
    return array;
}

Array.prototype.compact = function() {
    for (var i=this.length;i>=0;i--) {
        if ((this[i] == undefined) || (this[i] == '') || (this[i] == 'null'))  {
            this.splice(i, 1);
        }       
    }
    return this;
}

function form_show_found_info() {
    $('found_information').removeClassName('hidden');
    return false;
}
  
function form_hide_found_info() {
    $('found_information').addClassName('hidden');
    form_disable_submit();
    return false;
}

function form_enable_submit() {
	$('form_submit').disabled = false;
	return false;
}

function form_disable_submit() {
    $('form_submit').disabled = true;
    return false;
}

function add_new_tag_selector_observers(prefix) {
    $$('a.tag_selector').each(function(a){
        a.href = '#';
        Event.observe(a, 'click', function(e){
            toggle_tag(prefix, this.innerHTML);
        })
    })
    highlight_selected_tags(prefix);
    return false;
}

function highlight_selected_tags(prefix) {
    tags_field = $(prefix + '_tag_list');
    tags = tags_field.value.replace(/,\s*|\s*,/g,',').split(',');
    $$('a.tag_selector').each(function(s){
        s.removeClassName('tag_selected')
    })
    tags.each(function(t){
        tag = $('tag_' + t);
        if (tag != null) {
            tag.addClassName('tag_selected');
        }
    })
  
}

function toggle_tag(prefix, tag_name){
    tags_field = $(prefix + '_tag_list');
    if (tags_field != null) {
        tags = tags_field.value.replace(/,\s*|\s*,/g,',').split(',')
        if (tags.indexOf(tag_name) < 0) {
            //  console.log('adding ' + tag_name)
            tags.push(tag_name);
        } else {
            tags[tags.indexOf(tag_name)] = null;
        }
        tags = tags.unique().compact();
        tags_field.value = tags.join(',')
    }
    highlight_selected_tags(prefix);
    // console.log('Selected Tags => ' + tags_field.value);
    return false;
}



//experiment with clearing map and creating new overlay
function add_map_marker(){
	
    google_map.clearOverlays();//clear all overlays
	
    var a_99 = new GMarker(new GLatLng(30.472, -97.5932), {
        icon: new GIcon( G_DEFAULT_ICON, '/images/gmap/gicon_blue.png'),
        title: '1548 Fm 685 Pflugerville, TX 78660'
    });
    GEvent.addListener(a_99, 'click', function() {
        a_99_infowindow_function()
    });
    google_map.addOverlay(a_99);
	
//google_map.removeOverlay();
}

function new_store_create_observers(){
    se = $('select_existing_store')
    sne = $('select_not_existing_store')
    sdd = $('select_store_dropdown')
    Event.observe(se, 'click', new_store_select_existing)
    Event.observe(sne, 'click', new_store_select_not_existing)
    Event.observe(sdd, 'change', new_store_select_existing)
    new_store_select_existing();
}

function new_store_select_existing() {

    sdd = $('select_store_dropdown')
    sdd.disabled = false;
    $('store_form').setStyle({
        display: 'none'
    })
    $('store_name').disabled = true;
    $('store_description').disabled = true;
    $('store_id').value = sdd.value;

    form = $$("form")[0];
    form.method = 'post';
    form.action = '/stores/'+ $('store_id').value;
    set_form_method(form, 'put');

    if ($$('#store_new_addresses fieldset').length < 1) {
        new_store_insert_new_address_form()
    }
    new Ajax.Request('/stores/' + $('store_id').value + '/remote_update_new_store_address_list', {
        method: 'get'
    })
}

function new_store_select_not_existing() {
    form = $$("form")[0];
    form.method = 'post';
    form.action = '/stores';
    set_form_method(form, 'post');

    $('store_form').setStyle({
        display: 'block'
    });
    $('store_id').value = null;
    $('store_addresses').innerHTML = '';
    $('select_store_dropdown').disabled = true;
    $('store_name').disabled = false;
    $('store_description').disabled = false;
    if ($$('#store_new_addresses fieldset').length < 1) {
        new_store_insert_new_address_form()
    }
    new_store_reset_tag_cloud()
    add_new_tag_selector_observers("store");
}

function set_form_method(form_element, meth) {
    method_fields = $$("#" + form_element.id + " #_method");
    if (method_fields.length == 0) {
        //        s = '<input type=hidden value=post name=_method>';
        //        method_field_tag = document.createElement(s);
        method_field = new Element('input', {
            name: '_method',
            type: 'hidden',
            id: '_method'
        })
        form_element.appendChild(method_field);
    } else {
        method_field = method_fields[0]
    }
    method_field.value = meth;
}

function new_store_insert_new_address_form(){
    new Insertion.Bottom('store_new_addresses', $('new_address_form_template').innerHTML)
}

function new_store_reset_tag_cloud(){
    $('tag_cloud').innerHTML = $('new_address_tags_template').innerHTML;
}


// New Found Form Functions
function autofill_found_product_from_upc() {
    upc_field = $('found_product_upc')
    if (upc_field != null) {
        upc = upc_field.value;
        new Ajax.Request(('/products/' + upc + '.json'),
        {
            method: 'get',
            evalJSON: true,
            onSuccess:  function(transport){
                update_found_product_form_with_json(transport.responseJSON)
            }
        }
        )
    }
}

function update_found_product_form_with_json(product_json) {
    if (fill_found_product_form_with_json(product_json)) {
        highlight_selected_tags("found_product");
        $('found_price').focus();
    }
}

function fill_found_product_form_with_json(product_json) {
    p = product_json.product
    if ( p!=null ){
        $('found_product_id').value = p.id;
        $('found_product_description').value = p.description;
        $('found_product_brand').value = p.brand;
        $('found_product_size').value = p.size;
        $('found_product_tag_list').value = p.tag_list;
        return true;
    } else {
        return false;
    }
}

// End New Found Form Functions

RatingStars = Class.create({
    rated_by_user: false,
	initialize: function(constellation){
        this.stars = constellation.childElements()
        this.original_configuration = this.stars.collect(function(star){
            return star.className
        })
       	this.stars.each(function(star){
			star.observe('click', this.track.bindAsEventListener(this))
            star.observe('mouseover', this.moveTheStars.bindAsEventListener(this))
            constellation.observe('mouseout', this.hangTheMoon.bindAsEventListener(this))
        },this)
    },
    moveTheStars: function(e){
        this.hangTheMoon()
		
        firstStarISeeTonight = e.findElement('a')
		
        this.stars.each(function(starBright){
			starBright.className = "star no_star"
            if(this.stars.indexOf(starBright) > this.stars.indexOf(firstStarISeeTonight)){
                return
            }
			starBright.addClassName("user_star")
        },this)

        e.stop();
    },
    hangTheMoon: function(e){
        //resets all stars to their origional configuration
        this.stars.each(function(star, index){
			star.className = this.original_configuration[index]
        },this)
		
    },
	track: function(e){
		this.rated_by_user
	}
})
document.observe('dom:loaded', function(){
    $$('.rating_stars').each(function(constellation){
		if(constellation.childElements().first().tagName != "A"){return}
	
        new RatingStars(constellation)
    })
})

// <a href='#' class='toggler' targets='div1,div2' effect='blind' duration='0.3' text="Hide Text"> Show Text </a>
// <div id='div1'> ... </div>
// <div id='div2'> ... </div>
Toggler = Class.create({
	initialize: function(el){
			this.el = el
			this.el.observe('click', this.doToggle.bindAsEventListener(this))
	},
	getTargets: function(){
		return this.el.getAttribute("targets").split(',')
	},
	getEffect: function(){
		return this.el.getAttribute('effect')
	},
	getOptions: function(){
		return {duration: parseFloat(this.el.getAttribute('duration'))}
	},
	getText: function(){
		return this.el.getAttribute('text')
	},
	visible: function(){
		//true if targets are visible, false if targets are hidden
		return this.getTargets.first().visible()
	},
	setText: function(){
		transition = this.el.innerHTML
		this.el.innerHTML = this.getText()
		this.el.setAttribute("text", transition)
	},
	doToggle: function(e){
		this.el = e.element()

		
		target_effects = this.getTargets().collect(function(el){
			return new Effect.toggle(el, this.getEffect(), this.getOptions())
		}, this)
		this.setText()
		// 
		// new Effect.Parallel( target_effects, { 
		//   duration: 0.8,
		//   delay: 0.5
		// });
		// 
	}
})

document.observe("dom:loaded", function(){
	$$('a.toggler').each(function(el){
		new Toggler(el);		
	})
})

CategoryTagger = Class.create({
	initialize: function(el, target_el){
			this.el = el
			this.el.observe('click', this.insertTag.bindAsEventListener(this))
			this.target_el = $(target_el)
	},
	tag_present: function(tag){
		re = new RegExp("(,|\^) *"+tag+" *(,|$)")
		match = this.target_el.value.match(re)
		return(match)
	},
	addTag: function(tag){
		this.target_el.value += ", "+tag
	},
	clearTag: function(tag){
		re = new RegExp("(,|\^) *"+tag+" *")
		this.target_el.value = this.target_el.value.replace(re, "")		
	},
	insertTag: function(){
		if(this.el.checked){
			if(this.tag_present(this.el.value)){
			}
			else{
				this.addTag(this.el.value)	
			}
		}
		else{
			if(this.tag_present(this.el.value)){
				this.clearTag(this.el.value)	
			}
			else{
			}
		}
	}
})

document.observe("dom:loaded", function(){
	$$('input.tagger').each(function(el){
		new CategoryTagger(el, 'found_product_tag_list');		
	})
})

// This block looks for all the follow inputs and watches their select for form submittion
document.observe('dom:loaded',function(){
	try{ $$('input.follow_business, input.follow_location, input.follow_user').each(function(el){
		el.observe('click', follow_blu)
	})
	}catch(e){}
})

// Follow BLU (Business, Location, User) will watch for the click of the input and submit the associated form
function follow_blu(e){
	f = e.element().up('form')
	
	if(!current_user ){
		window.location='/signup'
		return
	}
	
	action = f.action;
	if(e.element().checked){
		action += '/follow'
	}else{
		action += '/unfollow'
	}
	new Ajax.Request(action , { method : 'get'} )
	
}

RecurrenceDateSelectForm = Class.create({
	initialize: function(form_el){
		this.showing = true
		this.toggler = $('toggle_recurrence');
		this.toggler.observe('click', this.toggle.bindAsEventListener(this));			
		if(this.enabled()){
			this.hide();
		}
    },
	enabled: function(){
		if($('found_has_recurrence').value == "false"){
			return(false);
		}else{
			return(true);
		}
	},
	toggle: function(event){
		event.stop();
		if(this.showing){
			this.hide();
		}else{
			this.show();
		}
	},
	hide: function(){
		this.showing = false
		$('found_has_recurrence').value = "true"
		$('found_activation_dates').hide();
		$('recurrence_form').show();
		this.toggler.innerHTML = "Remove Recurrence"
	},
	show: function(){
		this.showing = true
		$('found_has_recurrence').value = "false"
		$('found_activation_dates').show();
		$('recurrence_form').hide();
		this.toggler.innerHTML = "Add Recurrence"
	}
})
function embed_display_type(){
	if($('embed_map_display_both').checked){
		display_type = "both";
	}
	else if($('embed_map_display_map').checked){
		display_type = "map";
	}
	else{
		display_type = "list"
	}	
	return display_type;
}
function refresh_embed_view(){
	u_display = embed_display_type();
	embed_map('widget_preview') // refresh map
	get_embed_code()
	
	return false;
}
function get_embed_code(){
	str = '<script type="text/javascript">\n'
		str+= '\tvar u_display = "'+embed_display_type()+'";\n'
		str+= '\tvar wants_id= "'+wants_id+'";\n'
		str+= '</script>\n'
	str += '&lt;script src="http://wantandfound.com/javascripts/embedded_founds.js" type="text/javascript">&lt;/script>'
	$('widget_snipit').innerHTML = str.replace("<","&lt;").replace(">","&gt;").replace("</","&lt;/")
}