// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

var dialogOverlay;

var Dialog = {};
Dialog.Box = Class.create();
Object.extend(Dialog.Box.prototype, {
  initialize: function(id) {
    this.createOverlay();

    this.dialog_box = $(id);
    this.dialog_box.show = this.show.bind(this);
    this.dialog_box.hide = this.hide.bind(this);

    this.parent_element = this.dialog_box.parentNode;

    var e_dims = Element.getDimensions(this.dialog_box);
    var b_dims = Element.getDimensions(this.overlay);
    this.dialog_box.style.left = ((b_dims.width/2) - (e_dims.width/2)) + 'px';
    this.dialog_box.style.top = '12px';
  },

  createOverlay: function() {
    if($('dialog_overlay')) {
      this.overlay = $('dialog_overlay');
    } else {
      this.overlay = document.createElement('div');
      this.overlay.id = 'dialog_overlay';
      Object.extend(this.overlay.style, {
      	position: 'absolute',
      	top: 0,
      	left: 0,
      	zIndex: 90,
      	width: '100%',
      	height: '100%',
        backgroundColor: '#000',
      	display: 'none'
      });
      $('body').appendChild(this.overlay);
    }
  },

  moveDialogBox: function(where) {
    Element.remove(this.dialog_box);
    if(where == 'back')
      this.dialog_box = this.parent_element.appendChild(this.dialog_box);
    else
      this.dialog_box = this.overlay.parentNode.appendChild(this.dialog_box);
  },

  show: function() {
    this.overlay.style.height = $('body').getHeight()+200+'px';
    //this.overlay.onclick = this.hide.bind(this);
    this.selectBoxes('hide');
    new Effect.Appear(this.overlay, {duration: 0.1, from: 0.0, to: 0.3});
    this.moveDialogBox('out');
    this.dialog_box.style.display = ''
  },

  hide: function() {
    this.selectBoxes('show');
    if(this.overlay) new Effect.Fade(this.overlay, {duration: 0.1});
    this.dialog_box.style.display = 'none';
    this.moveDialogBox('back');
    $A(this.dialog_box.getElementsByTagName('input')).each(function(e){if(e.type!='submit')e.value=''});
    if(this.overlay) Element.remove(this.overlay);
    this.overlay = null;
  },

  selectBoxes: function(what) {
    $A(document.getElementsByTagName('select')).each(function(select) {
      Element[what](select);
    });

    if(what == 'hide')
      $A(this.dialog_box.getElementsByTagName('select')).each(function(select){Element.show(select)})
  }
});

var mostRecentScreenName = "";
var addNoteWatcherArr = new Array();

function checkForHTMLTags(strInputCode){
    var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
    if(strInputCode.length != strTagStrippedText.length)
    {
        alert("Please remove all HTML from your content before submission.");
        return true;
    }
    return false;
}

// Removes leading whitespaces
function LTrim( value ) {

	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");

}

// Removes ending whitespaces
function RTrim( value ) {

	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");

}

// Removes leading and ending whitespaces
function trim( value ) {

	return LTrim(RTrim(value));

}

function search_submit() {
    $("sitesearch").submit();
}

function search_box_submit(location) {
    $("searchbox_"+location).submit();
}

var order_dir = ["asc", "desc"];
var order_dir_index = 0;
var most_recent_search_type = "name"
function reload_listing(parent_id, destination_name, listing_type, column, filter, type)
{
    if((most_recent_search_type == column) && order_dir_index == 0){
        order_dir_index = 1;
    }
    else{
        order_dir_index = 0;
    }
    most_recent_search_type = column;
    new Ajax.Updater('clm_content', '/clm/reload_clm_content?parent_id=' + parent_id + '&dest_name=' + destination_name + '&content_type=' + listing_type + '_listing&order_by=' + column + '&order_dir=' + order_dir[order_dir_index] + '&filter=' + filter + '&parent_type=' + type,{asynchronous:true, evalScripts:true}); return false;
}

function open_dialog_overlay(div_id) {

    if(dialogOverlay) dialogOverlay.hide();
    if ( $(div_id) ) {
        dialogOverlay = new Dialog.Box(div_id);
        dialogOverlay.show();
    }
}

function close_dialog_overlay() {
    if(dialogOverlay) dialogOverlay.hide();
}

function open_confirm_trip_dialog() {
    open_dialog_overlay("my_trips_confirm_popup");
}

function open_confirm_sign_up_dialog() {
    open_dialog_overlay("my_sign_up_confirm_popup");
}

function open_create_a_trip(trip_form, item_id, item_name, item_type, item_description, top, left)
{
    trip_form.elements['screen_name'].value = mostRecentScreenName;
    sub_title = $("my_trips_title");
    if(item_id && item_type)
    {
        sub_title.innerHTML = "Create a Trip For " + item_name;
        trip_form.elements['item_id'].value = item_id;
        trip_form.elements['item_type'].value = item_type;
        trip_form.elements['item_description'].value = item_description;
    }
    else
    {
        sub_title.innerHTML = "Create a Trip";
    }
    pop_win = $("pop_win_create");
    if(top && left)
    {
        pop_win.style.top = top;
        pop_win.style.left = left;
    }
    if(dialogOverlay) dialogOverlay.hide();
    dialogOverlay = new Dialog.Box('my_trips_popup_wrapper');
    dialogOverlay.show();
}

function submit_my_trip_form(trip_form)
{
    if(!(trim(trip_form.elements['item_id'].value).length == 0))
    {
        return 0;
    }
    else if($('submit_add_my_trips'))
    {
        return 1;
    }
    return -1;
}

function save_my_trip(trip_form, user_id, reg_url)
{
    mostRecentScreenName = trip_form.elements['screen_name'].value;
    var submit_form = submit_my_trip_form(trip_form);
    if(
        (!trip_form.elements['trip_name'].value || trim(trip_form.elements['trip_name'].value).length == 0) ||
        (!trip_form.elements['screen_name'].value || trim(trip_form.elements['screen_name'].value).length == 0)
      )
    {
        var errorDiv = $("my_trips_errors");
        errorDiv.innerHTML = "<span class=\"red\">Please complete all required fields.</span>";
        Element.show(errorDiv);
    }
    else
    {
        Element.hide($("my_trips_errors"));
        if(submit_form == -1)
        {
            new Ajax.Request('/mytrips/ajax_add_trip',{asynchronous:false, method:'post',
                postBody:'trip_name=' + escape(trip_form.elements['trip_name'].value) +
                            '&description=' + escape(trip_form.elements['description'].value) +
                            '&screen_name=' + escape(trip_form.elements['screen_name'].value) +
                            '&item_id=' + trip_form.elements['item_id'].value +
                            '&item_type=' + trip_form.elements['item_type'].value +
                            '&item_description=' + escape(trip_form.elements['item_description'].value)});
            Element.hide($('my_trips_popup_wrapper'));
            if(!user_id || trim(user_id).length == 0)
            {
                window.location.href = reg_url;
            }
            else
            {
                if ( $('confirm_a_trip_name') ) {
                    $('confirm_a_trip_name').innerHTML=trip_form.elements['trip_name'].value;
                }
                new Ajax.Updater('add_to_trip_trips', '/mytrips/reload_user_trips', {asynchronous:true, evalScripts:true, method:'post', postBody:'user_id=' + user_id});
                new Ajax.Updater('my_trips_wrapper', '/mytrips/view_module', {asynchronous:true, evalScripts:true, method:'post', postBody:'trip_added=true', onSuccess: open_confirm_trip_dialog });
                Element.hide($('my_trips_popup_wrapper'));
            }
            clear_and_close(trip_form, null);
        }
        else
        {
            trip_form.elements['redirect_to'].value = submit_form;
            trip_form.submit();
        }
        return true;
    }
}

function toggle_traffic_tabs(id_1,id_2,id_3)
{
    Element.show("traffic_" + id_1);
    Element.hide("traffic_" + id_2);
    Element.hide("traffic_" + id_3);
    Element.show("tlink_" + id_1 + "_on");
    Element.hide("tlink_" + id_1 + "_off");
    Element.show("tlink_" + id_2 + "_off");
    Element.hide("tlink_" + id_2 + "_on");
    Element.show("tlink_" + id_3 + "_off");
    Element.hide("tlink_" + id_3 + "_on");
}

function update_map_markers()
{
	current_marker_group.deactivate();
	selection = $('google_map_listings');
	current_marker_group = window[selection.options[selection.selectedIndex].value];
	current_marker_group.activate();
}

var add_to_trip_original_x = "25%";
var add_to_trip_original_y = "25%";


function open_add_to_trip(listing_id, listing_name, listing_type, parent)
{
    pop_win = $('pop_addytrip');
    sub_title = $("add_to_my_trips_sub_title");
    sub_title.innerHTML = listing_name;
    add_to_trip_form = $('add_item_to_trip_form');
    add_to_trip_form.elements['item_id'].value = listing_id;
    add_to_trip_form.elements['item_name'].value = listing_name;
    add_to_trip_form.elements['item_type'].value = listing_type;
    setWindowPosition(pop_win, parent);
    if(dialogOverlay) dialogOverlay.hide();
    dialogOverlay = new Dialog.Box("add_to_my_trips_popup_wrapper");
    dialogOverlay.show();
    if(parent) new Effect.ScrollTo("pop_addytrip", {offset: -50});
}

function add_item_to_trip(user_id, add_to_trip_form, reg_url)
{
    trip_id = add_to_trip_form.elements['trip_id'].value;
    if(trip_id && trim(trip_id).length > 0)
    {
        new Ajax.Request('/mytrips/ajax_add_trip',{asynchronous:false, method:'post',
            postBody:'trip_id=' + add_to_trip_form.elements['trip_id'].value +
                        '&screen_name=' + escape(mostRecentScreenName) +
                        '&item_id=' + add_to_trip_form.elements['item_id'].value +
                        '&item_type=' + add_to_trip_form.elements['item_type'].value +
                        '&item_description=' + escape(add_to_trip_form.elements['item_description'].value)});
        Element.hide($('add_to_my_trips_popup_wrapper'));
        clear_and_close(add_to_trip_form, null);
        if(!user_id || trim(user_id).length == 0)
        {
            window.location.href = reg_url;
        }
        else
        {
            window.location.href = "/mytrips/view_trip/" + trip_id;
        }
    }
    else{
        alert("Please select a Trip to add this ")
    }
}

function create_new_trip_for_listing(add_to_trip_form)
{
    var top = null;
    var left = null;
    trip_form = $('add_my_trips_form');
    pop_win = $("pop_addytrip");
    top = pop_win.style.top;
    left = pop_win.style.left;
    if(add_to_trip_form && add_to_trip_form.elements)
    {
        open_create_a_trip(trip_form, add_to_trip_form.elements['item_id'].value,
            add_to_trip_form.elements['item_name'].value,
            add_to_trip_form.elements['item_type'].value,
            add_to_trip_form.elements['item_description'].value,
            top,
            left);
        add_to_trip_form.reset();
   }
}

function clear_and_close(target_form, target_div)
{
    if(dialogOverlay) dialogOverlay.hide();
    target_form.reset();
    for(i = 0; i < target_form.elements.length; i++)
    {
        if(target_form.elements[i].type == "hidden")
        {
            target_form.elements[i].value = "";
        }
    }
}

function remove_trip_item(trip_id, item_id) {
    new Ajax.Request('/mytrips/delete_trip_item',{asynchronous:true, method:'post',
            postBody:'trip_id=' + trip_id + '&item_id=' + item_id});
    new Effect.SlideUp('trip_item_' + item_id);
}

function open_my_trips_date_selector(no_of_days)
{
    day_selector_form = $('date_selector');
    day_list = day_selector_form.elements['no_of_days'];
    day_options = day_list.options;
    day_list.selectedIndex = (no_of_days > 0 ? (no_of_days - 1) : 0);
    day_options[no_of_days > 0 ? (no_of_days - 1) : 0].selected = true;
    Element.show($("popup_enter_date_win_wrapper"));
}

function close_my_trips_date_selector()
{
    Element.hide($("popup_enter_date_win_wrapper"));
}

var current_item_being_moved = '';
var current_targeted_parent = '';

function chgd(e)
{
    current_item_being_moved = e.id;
    current_targeted_parent = e.parentNode.id;
}

function update_div_name(e)
{
    new Ajax.Request('/mytrips/update_item_parent',{asynchronous:true, method:'post',
            postBody:'parent_id=' + current_targeted_parent + '&item_id=' + current_item_being_moved });
}

MoveItemWatcher = Class.create();

//defining the rest of the class implementation
MoveItemWatcher.prototype = {
    initialize: function(id) {
        this.id = id;
        this.closeOnTarget = false;
        this.listener = this.handleEvent.bindAsEventListener(this);
        Event.observe(document.body, 'click', this.listener);
    },

    handleEvent: function(evt) {
        var target = this.getTargetElement(evt);
        if (target.id != 'move_link_'+this.id) {
            this.hideMove();
        } else if (target.id == 'move_link_'+this.id && this.closeOnTarget) {
            this.hideMove();
        } else {
            this.closeOnTarget = true;
        }

    },

    hideMove: function() {
        if (null != this.id && null != $('move_link_'+this.id)) {
            Element.remove('move_item_list_'+this.id);
            this.teardown();
        }
    },

    teardown: function() {
        this.id = null;
        this.closeOnTarget = false;
        Event.stopObserving(document.body, 'click', this.listener);
    },

    getTargetElement: function(e) {
        var targ;
        if (!e) var e = window.event;
        if (e.target) targ = e.target;
        else if (e.srcElement) targ = e.srcElement;
        if (targ.nodeType == 3) // defeat Safari bug
            targ = targ.parentNode;
        return targ;
    }
};

var moveItemWatcher;

function showMove(id, dayArr, type, offsetTop, offsetLeft) {
    if(!$('move_item_list_'+id))
    {
        if (moveItemWatcher != null) {
            moveItemWatcher.hideMove();
        }
        // Build the list of items
        var appendTo = window.document.getElementsByTagName("body")[0];
        var move_hook = $('move_item_hook_' + id);
        var posArr = Position.cumulativeOffset(move_hook);
        var position_left = posArr[0] - offsetTop;
        var position_top = posArr[1] + offsetLeft;
        var element = Builder.node('div',{id:'move_item_list_'+id, className:'day-options', style: 'position: absolute; top: ' + position_top + 'px; left: ' + position_left + 'px'});
        var shadow = Builder.node('div',{className:'pop-shadow'});
        var move_item = $('trip_item_' + id);
        var move_from = move_item.parentNode;
        var list = Builder.node('ul');
        var listItem;
        for(i = 0; i < dayArr.length; i++)
        {
            listItem = Builder.node('li');
            if(dayArr[i][0] == -1)
            {
                if(move_from.id.indexOf('day_') == -1)
                {
                    listItem.appendChild(Builder.node('span', dayArr[i][1]));
                }
                else
                {
                    listItem.appendChild(Builder.node('a', {href:'javascript:void(0);', onclick:'move_item(' + id + ',' + dayArr[i][0] + ', \'' + type + '\');return false;'}, dayArr[i][1]));
                }
            }
            else if(move_from.id == ('day_' + dayArr[i][0]))
            {
                listItem.appendChild(Builder.node('span', 'To ' + dayArr[i][1]));
            }
            else
            {
                listItem.appendChild(Builder.node('a', {href:'javascript:void(0);', onclick:'move_item(' + id + ',' + dayArr[i][0] + ', \'' + type + '\');return false;'}, 'To ' + dayArr[i][1]));
            }
            list.appendChild(listItem);
        }
        shadow.appendChild(list);
        element.appendChild(shadow);
        appendTo.appendChild(element);
        moveItemWatcher = new MoveItemWatcher(id);
    }
    else if (moveItemWatcher != null) {
        moveItemWatcher.hideMove();
    }
}

function move_item(item_id, move_to, type)
{
    var item = $('trip_item_' + item_id);
    var move_from = item.parentNode;
    move_from.removeChild(item);
    if(move_to == -1)
    {
        switch(type)
        {
            case 'places-to-stay':
                $('places_to_stay').appendChild(item);
                break;
            case 'places-to-eat':
                $('places_to_eat').appendChild(item);
                break;
            case 'things-to-do':
                $('things_to_do').appendChild(item);
                break;
            case 'trip-articles':
                $('articles_blog_posts').appendChild(item);
                break;
        }
        current_targeted_parent = "";
    }
    else
    {
        $('day_' + move_to).appendChild(item);
        current_targeted_parent = 'day_' + move_to;
    }
    current_item_being_moved = 'trip_item_' + item_id;
    update_div_name();
}

AddNoteWatcher = Class.create();

//defining the rest of the class implementation
AddNoteWatcher.prototype = {
    initialize: function(id, state, read_view) {
        this.id = id;
        this.state = state;
        this.closeOnTarget = false;
        this.read_view = read_view;
        this.listener = this.handleEvent.bindAsEventListener(this);
        Event.observe(document.body, 'click', this.listener);
    },

    handleEvent: function(evt) {
        var target = this.getTargetElement(evt);
        if (target.id == 'add_note_link_'+this.id) {
            if(this.closeOnTarget){
                this.hideAddNote();
            }
            else
            {
                this.closeOnTarget = false;
            }
        }
        else if(target.id == 'close_add_note_'+this.id)
        {
            if(this.read_view)
            {
                Element.show(this.read_view);
                Element.hide('form_container_' + this.id);
            }
            else
            {
                this.hideAddNote();
            }
        }
        else if(target.id == 'save_add_note_'+this.id)
        {
            this.saveAddNote();
        }
        else if(target.id == 'edit_add_note_'+this.id)
        {
            this.editAddNote();
        }
        else if(target.id == 'delete_add_note_'+this.id)
        {
            this.deleteAddNote();
        }
    },

    hideAddNote: function() {
        if($('add_note_dialog_'+this.id))
        {
            Element.remove('add_note_dialog_'+this.id);
        }
        this.teardown();
    },

    saveAddNote: function() {
        if(!checkForHTMLTags($('item_note_' + this.id).value))
        {
            new Ajax.Request('/mytrips/save_item_note',{asynchronous:true, method:'post',
                postBody:'id=' + this.id + '&notes=' + escape($('item_note_' + this.id).value)});
            $('note_body_' + this.id).innerHTML = $('item_note_' + this.id).value;
            Element.show('note_container_'+ this.id);
            Element.hide('form_container_'+this.id);
            button = $('add_note_button_' + this.id);
            button.removeChild($("add_note_link_" + this.id));
            button.innerHTML = "Add A Note";
            this.read_view = $('note_container_'+ this.id);
        }
    },

    openForm: function()
    {
        Element.hide('note_container_'+this.id);
        Element.show('form_container_'+ this.id);
    },

    editAddNote: function() {
        $('item_note_' + this.id).value = $('note_body_' + this.id).lastChild.nodeValue;
        this.openForm();
    },

    deleteAddNote: function() {
        new Ajax.Request('/mytrips/save_item_note',{asynchronous:true, method:'post',
                postBody:'id=' + this.id + '&notes='});
        button = $('add_note_button_' + this.id);
        button.innerHTML = "";
        button.appendChild(Builder.node('a', {href: "javascript:void(0);", id: "add_note_link_" + this.id, onclick: "addNote(" + this.id + "); return false;"}, 'Add a Note'));
        this.hideAddNote();
    },

    teardown: function() {
        this.id = null;
        this.closeOnTarget = false;
        Event.stopObserving(document.body, 'click', this.listener);
    },

    getTargetElement: function(e) {
        var targ;
        if (!e) var e = window.event;
        if (e.target) targ = e.target;
        else if (e.srcElement) targ = e.srcElement;
        if (targ.nodeType == 3) // defeat Safari bug
            targ = targ.parentNode;
        return targ;
    }
};

function displayAddNote(id, state)
{
    if(!$('add_note_dialog_'+id) || state == "edit")
    {
        var element;
        var note_container;
        // Build the list of items
        if(state == "edit" && $('note_container_'+id))
        {
            element = $('add_note_dialog_'+id);
            note_container = $('note_container_'+id);
        }
        else
        {
            element = Builder.node('div',{id:'add_note_dialog_'+id, className:'add-note'});
            note_container = Builder.node('div', {id:'note_container_'+id, style: 'display: none'});
            var note_title = Builder.node('p', 'Note');
            var note_body = Builder.node('p', {id: 'note_body_' + id, className: 'copy'});
            var note_options = Builder.node('p', {className: 'options'});
            note_options.appendChild(Builder.node('a', {id: 'edit_add_note_'+id, href:'javascript:void(0);'}, 'edit'));
            note_options.appendChild(Builder.node('a', {id: 'delete_add_note_'+id, href:'javascript:void(0);', onclick:'delete_note();'}, 'delete'));
            note_container.appendChild(note_title);
            note_container.appendChild(note_body);
            note_container.appendChild(note_options);
            element.appendChild(note_container);
        }
        var form_container = Builder.node('div', {id:'form_container_'+id, style: 'display: none'});
        var title = Builder.node('p', 'Add a Note');
        var list = Builder.node('ul', {className:'add-note-btns'});
        var listItem1 = Builder.node('li', {className: 'btn-80x25'});
        var listItem2 = Builder.node('li', {className: 'btn-80x25'});
        listItem1.appendChild(Builder.node('a', {id: 'save_add_note_'+id, href:'javascript:void(0);'}, 'Save'));
        listItem2.appendChild(Builder.node('a', {id: 'close_add_note_'+id, href:'javascript:void(0);'}, 'Cancel'));
        list.appendChild(listItem1);
        list.appendChild(listItem2);
        form = Builder.node('form');
        if(state == "edit")
        {
            textarea = Builder.node('textarea', {id: 'item_note_' + id, wrap:'virtual', onclick:'clearField(this, \'Enter text here\' );'}, 'Enter text here');
        }
        else
        {
            textarea = Builder.node('textarea', {id: 'item_note_' + id, onclick:'clearField(this, \'Enter text here\' );', wrap:'virtual'}, 'Enter text here');
        }
        form.appendChild(textarea);
        form_container.appendChild(title);
        form_container.appendChild(list);
        form_container.appendChild(form);
        element.appendChild(form_container);
        $("add_note_hook_" + id).appendChild(element);
        addNoteWatcherArr[id + ""] = new AddNoteWatcher(id, state, (state == "edit") ? note_container : null);
        if(state == "add")
        {
            addNoteWatcherArr[id + ""].openForm();
        }
        else if(state == "edit")
        {
            addNoteWatcherArr[id + ""].editAddNote();
        }
    }
    else if (addNoteWatcherArr[id + ""] != null) {
        addNoteWatcherArr[id + ""].hideAddNote();
    }
}

function editNote(id)
{
    displayAddNote(id, "edit");
}

function addNote(id)
{
    displayAddNote(id, "add");
}

function deleteNote(id)
{
    addNoteWatcherArr[id + ""] = new AddNoteWatcher(id);
    addNoteWatcherArr[id + ""].deleteAddNote();
}

function clearField(e, default_text) {
    if (typeof default_text=="undefined" || (default_text==trim(e.value)) ) {
        e.value = "";
    }
    e.style.fontStyle = "normal";
    e.style.color = "#333333";
}

function print_mytrips(type, id)
{
    if (type=="all") {
        Element.hide('print_trip_popup_wrapper');
        window.print();
    } else {
        Element.hide('print_trip_popup_wrapper');
        window.open('/mytrips/view_itinerary/'+id,'_new','height=500,width=600')
    }
}

function toggle_multimedia(tab1, tab2) {
    if ( $(tab1) && $(tab2) ) {
        Element.toggle($(tab1));
        Element.toggle($(tab2));
    }
}

function open_child_window(url)
{
    window.open(url, '_new', 'height=600,width=800');
}

function load_yourscene_listing_images(listing_type, listing_id) {
    new Ajax.Updater('yourscene_images','/listing_images/'+listing_type+'_'+listing_id, {method:'get', asynchronous:true});
}

function load_yourscene_dest_images(album_id) {
    new Ajax.Updater('u_tab','/multimedia_user_images/'+album_id, {method:'get', asynchronous:true, insertion:Insertion.Bottom});
}

function load_yourscene_homepage_images() {
    new Ajax.Updater('u_tab','/multimedia_user_images_homepage', {method:'get', asynchronous:true, insertion:Insertion.Bottom});
}

function load_yourscene_promo_images() {
    new Ajax.Updater('message','/photo_sharing', {method:'get', asynchronous:true, insertion:Insertion.After});
}

function move_ad_sense() {
	var ad_content = $('sponsored');
	var ad_container = $('ad_sense_container');
	if (ad_content && ad_container) {
		ad_content.parentNode.removeChild(ad_content);
		ad_container.parentNode.replaceChild(ad_content, ad_container);
		ad_content.display = "block";
	}
}

function validate_email(email){
    var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
    if ( filter.test(email) )
   {
      return true;
    }
    return false;
}

// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download.
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================

var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
function LZ(x){return(x<0||x>9?"":"0")+x}
function isDate(val,format){var date=getDateFromFormat(val,format);if(date==0){return false;}return true;}
function compareDates(date1,dateformat1,date2,dateformat2){var d1=getDateFromFormat(date1,dateformat1);var d2=getDateFromFormat(date2,dateformat2);if(d1==0 || d2==0){return -1;}else if(d1 > d2){return 1;}return 0;}
function formatDate(date,format){format=format+"";var result="";var i_format=0;var c="";var token="";var y=date.getYear()+"";var M=date.getMonth()+1;var d=date.getDate();var E=date.getDay();var H=date.getHours();var m=date.getMinutes();var s=date.getSeconds();var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;var value=new Object();if(y.length < 4){y=""+(y-0+1900);}value["y"]=""+y;value["yyyy"]=y;value["yy"]=y.substring(2,4);value["M"]=M;value["MM"]=LZ(M);value["MMM"]=MONTH_NAMES[M-1];value["NNN"]=MONTH_NAMES[M+11];value["d"]=d;value["dd"]=LZ(d);value["E"]=DAY_NAMES[E+7];value["EE"]=DAY_NAMES[E];value["H"]=H;value["HH"]=LZ(H);if(H==0){value["h"]=12;}else if(H>12){value["h"]=H-12;}else{value["h"]=H;}value["hh"]=LZ(value["h"]);if(H>11){value["K"]=H-12;}else{value["K"]=H;}value["k"]=H+1;value["KK"]=LZ(value["K"]);value["kk"]=LZ(value["k"]);if(H > 11){value["a"]="PM";}else{value["a"]="AM";}value["m"]=m;value["mm"]=LZ(m);value["s"]=s;value["ss"]=LZ(s);while(i_format < format.length){c=format.charAt(i_format);token="";while((format.charAt(i_format)==c) &&(i_format < format.length)){token += format.charAt(i_format++);}if(value[token] != null){result=result + value[token];}else{result=result + token;}}return result;}
function _isInteger(val){var digits="1234567890";for(var i=0;i < val.length;i++){if(digits.indexOf(val.charAt(i))==-1){return false;}}return true;}
function _getInt(str,i,minlength,maxlength){for(var x=maxlength;x>=minlength;x--){var token=str.substring(i,i+x);if(token.length < minlength){return null;}if(_isInteger(token)){return token;}}return null;}
function getDateFromFormat(val,format){val=val+"";format=format+"";var i_val=0;var i_format=0;var c="";var token="";var token2="";var x,y;var now=new Date();var year=now.getYear();var month=now.getMonth()+1;var date=1;var hh=now.getHours();var mm=now.getMinutes();var ss=now.getSeconds();var ampm="";while(i_format < format.length){c=format.charAt(i_format);token="";while((format.charAt(i_format)==c) &&(i_format < format.length)){token += format.charAt(i_format++);}if(token=="yyyy" || token=="yy" || token=="y"){if(token=="yyyy"){x=4;y=4;}if(token=="yy"){x=2;y=2;}if(token=="y"){x=2;y=4;}year=_getInt(val,i_val,x,y);if(year==null){return 0;}i_val += year.length;if(year.length==2){if(year > 70){year=1900+(year-0);}else{year=2000+(year-0);}}}else if(token=="MMM"||token=="NNN"){month=0;for(var i=0;i<MONTH_NAMES.length;i++){var month_name=MONTH_NAMES[i];if(val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()){if(token=="MMM"||(token=="NNN"&&i>11)){month=i+1;if(month>12){month -= 12;}i_val += month_name.length;break;}}}if((month < 1)||(month>12)){return 0;}}else if(token=="EE"||token=="E"){for(var i=0;i<DAY_NAMES.length;i++){var day_name=DAY_NAMES[i];if(val.substring(i_val,i_val+day_name.length).toLowerCase()==day_name.toLowerCase()){i_val += day_name.length;break;}}}else if(token=="MM"||token=="M"){month=_getInt(val,i_val,token.length,2);if(month==null||(month<1)||(month>12)){return 0;}i_val+=month.length;}else if(token=="dd"||token=="d"){date=_getInt(val,i_val,token.length,2);if(date==null||(date<1)||(date>31)){return 0;}i_val+=date.length;}else if(token=="hh"||token=="h"){hh=_getInt(val,i_val,token.length,2);if(hh==null||(hh<1)||(hh>12)){return 0;}i_val+=hh.length;}else if(token=="HH"||token=="H"){hh=_getInt(val,i_val,token.length,2);if(hh==null||(hh<0)||(hh>23)){return 0;}i_val+=hh.length;}else if(token=="KK"||token=="K"){hh=_getInt(val,i_val,token.length,2);if(hh==null||(hh<0)||(hh>11)){return 0;}i_val+=hh.length;}else if(token=="kk"||token=="k"){hh=_getInt(val,i_val,token.length,2);if(hh==null||(hh<1)||(hh>24)){return 0;}i_val+=hh.length;hh--;}else if(token=="mm"||token=="m"){mm=_getInt(val,i_val,token.length,2);if(mm==null||(mm<0)||(mm>59)){return 0;}i_val+=mm.length;}else if(token=="ss"||token=="s"){ss=_getInt(val,i_val,token.length,2);if(ss==null||(ss<0)||(ss>59)){return 0;}i_val+=ss.length;}else if(token=="a"){if(val.substring(i_val,i_val+2).toLowerCase()=="am"){ampm="AM";}else if(val.substring(i_val,i_val+2).toLowerCase()=="pm"){ampm="PM";}else{return 0;}i_val+=2;}else{if(val.substring(i_val,i_val+token.length)!=token){return 0;}else{i_val+=token.length;}}}if(i_val != val.length){return 0;}if(month==2){if( ((year%4==0)&&(year%100 != 0) ) ||(year%400==0) ){if(date > 29){return 0;}}else{if(date > 28){return 0;}}}if((month==4)||(month==6)||(month==9)||(month==11)){if(date > 30){return 0;}}if(hh<12 && ampm=="PM"){hh=hh-0+12;}else if(hh>11 && ampm=="AM"){hh-=12;}var newdate=new Date(year,month-1,date,hh,mm,ss);return newdate.getTime();}
function parseDate(val){var preferEuro=(arguments.length==2)?arguments[1]:false;generalFormats=new Array('y-M-d','MMM d, y','MMM d,y','y-MMM-d','d-MMM-y','MMM d');monthFirst=new Array('M/d/y','M-d-y','M.d.y','MMM-d','M/d','M-d');dateFirst =new Array('d/M/y','d-M-y','d.M.y','d-MMM','d/M','d-M');var checkList=new Array('generalFormats',preferEuro?'dateFirst':'monthFirst',preferEuro?'monthFirst':'dateFirst');var d=null;for(var i=0;i<checkList.length;i++){var l=window[checkList[i]];for(var j=0;j<l.length;j++){d=getDateFromFormat(val,l[j]);if(d!=0){return new Date(d);}}}return null;}

// ======== END OF DATE CODE

function checkDateForm(date_form)
{
    if(isDate((date_form.elements["date[day]"].value + " " + date_form.elements["date[month]"].value + " " + date_form.elements["date[year]"].value), 'd M yyyy'))
    {
        date_form.submit();
    }
    else
    {
        //alert(getDateFromFormat(date_form.elements["date[day]"].value + " " + date_form.elements["date[month]"].value + " " + date_form.elements["date[year]"].value), 'dd MM yyyy');
        alert("Please provide a valid start date");
    }
}

//-----------------------------
//------Expedia Javascript-----
//-----------------------------

function SC(el1,el2){if (DE('CalFrame') == null){return;}el1.select();ShowCalendar(el1,el1,el2,CalS,CalE);}
function HCal(e){if (DE('CalFrame') != null){CancelCal();}}

function DE(el){return document.getElementById(el);}
function hw(id) {

    if(DE('sFlt').checked == false){
        DE('flt').style.display = 'none';
        DE("s1").style.display = 'none';
    }else{
        DE("s1").style.display = 'block';
    }
    if(DE('sHot').checked == false){
        DE("s2").style.display = 'none';
        DE('hot').style.display = 'none';
    }else{
        DE("s2").style.display = 'block';
    }
    if(DE('sPac').checked == false){
        DE("s4").style.display = 'none';
        DE('pac').style.display = 'none';
    }else{
        DE("s4").style.display = 'block';
    }
    if(DE('sCru').checked == false){
        DE("s5").style.display = 'none';
        DE('cru').style.display = 'none';
    }else{
        DE("s5").style.display = 'block';
    }
    if(DE('sTsh').checked == false){
        DE("s6").style.display = 'none';
        DE('tsh').style.display = 'none';
    }else{
        DE("s6").style.display = 'block';
    }
    if(DE('sCar').checked == false){
        DE("s3").style.display = 'none';
        DE('car').style.display = 'none';
    }else{
        DE("s3").style.display = 'block';
    }
    DE(id).style.display = 'block';
    var d = document.Wiz;
}
function chkBrowser(){this.ver=navigator.appVersion;this.dom=document.getElementById?1:0;this.ie5=(this.ver.indexOf("MSIE 5")>-1 && this.dom)?1:0;this.ie4=(document.all && !this.dom)?1:0;this.ns5=(this.dom && parseInt(this.ver) >= 5) ?1:0;this.ns4=(document.layers && !this.dom)?1:0;this.bVer=(this.ie5 || this.ie4 || this.ns4 || this.ns5);return this;}bVer=new chkBrowser();ns4 = (document.layers)? true:false;ie4 = (document.all)? true:false;
function AttB(f){if(bVer.ie4)f.style.display='block';}
function AttN(f){if(bVer.ie4)f.style.display='none';}
function show(idLayer,idParent){cLayer=bVer.dom?document.getElementById(idLayer).style:bVer.ie4?document.all[idLayer].style:bVer.ns4?idParent?document[idParent].document[idLayer]:document[idLayer]:0;cLayer.display='block';var d=document.Wiz;}
function hide(idLayer,idParent){cLayer=bVer.dom?document.getElementById(idLayer).style:bVer.ie4?document.all[idLayer].style:bVer.ns4?idParent?document[idParent].document[idLayer]:document[idLayer]:0;cLayer.display='none';}
function mrd(i){if (i==1) {hide('hotrm2'); hide('hotrm3'); hide('rm1txt');}if (i==2) {show('hotrm2'); hide('hotrm3'); show('rm1txt');}if (i==3) {show('hotrm2'); show('hotrm3'); show('rm1txt');}}
function SetPkgType(i) {
    var PkgWithFlightVal = document.PkgFormWithFlight.Destname.value;
    var PkgNoFlightVal = document.PkgFormNoFlight.Destname.value;
    sActivePack = i;
    //Hotel and card
    if (3 == i) {
        hide('PkgWithFlight');
        hide('PkgWithFlightCar');
        show('PkgNoFlight');
        if (PkgWithFlightVal.length>0) {
            document.PkgFormNoFlight.Destname.value = PkgWithFlightVal;
        }

        // Flight and car
    } else if (5 == i) {
        hide('PkgWithFlight');
        hide('PkgNoFlight');
        show('PkgWithFlightCar');

    } else {
        hide('PkgNoFlight');
        hide('PkgWithFlightCar');
        show('PkgWithFlight');
        if (PkgNoFlightVal.length>0) {
            document.PkgFormWithFlight.Destname.value = PkgNoFlightVal;
        }
        document.PkgFormWithFlight.PackageType.value = i;
    }
}

function sendForm() {
    if (DE('sFlt').checked) {
        document.FltForm.submit();
    }
    if (DE('sHot').checked) {
        document.HotForm.submit();
    }
    if (DE('sPac').checked) {
        if(sActivePack == 5){
            document.PkgFormWithFlightCar.submit();
        }
        if(sActivePack == 3){
            document.PkgFormNoFlight.submit();
        }
        if(sActivePack == 2 || sActivePack == 1){
            document.PkgFormWithFlight.submit();
        }
    }
    if (DE('sCru').checked) {
        document.CruForm.submit();
    }
    if (DE('sTsh').checked) {
        document.TshForm.action = "http://www.expedia.com/pubspec/scripts/eap.asp";
        document.TshForm.submit();
    }
    if (DE('sCar').checked) {
        document.CarForm.submit();
    }
}

function addCodeToFunction(func,code){
    if(func == undefined)
		return code;
    else{
		return function(){
			func();
			code();
		}
    }
}

var win = null;
function newWin(mypage,myname,w,h){
    var LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
    var TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
    var settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars=no'
    win = window.open(mypage,myname,settings)
    if(win.window.focus){win.window.focus();}
}

var order_dir_index = 0;
var order_by_id = 0;

function updateOrderImg()
{
    if (order_by_id == 1){
			if(order_dir_index == 1){
        $(order_by_id + "").src = "/images/short_up.gif";
    	}
    	else{
        $(order_by_id + "").src = "/images/short_dwn.gif";
    	}
		}else{
			if(order_dir_index == 0){
        $(order_by_id + "").src = "/images/short_up.gif";
    	}
    	else{
        $(order_by_id + "").src = "/images/short_dwn.gif";
    	}
		}
}

function reorderSearch(p, b, l, a, query, order_by, type)
{
    if((order_by_id == order_by) && order_dir_index == 0){
        order_dir_index = 1;
    }
    else{
        order_dir_index = 0;
    }
    if($(order_by_id + "") && (order_by_id != order_by))
    {
        $(order_by_id + "").src = "/images/dot_clear.gif";
    }
    order_by_id = order_by;
    new Ajax.Updater('result_list', '/search/reorder_' + type + '/?p=' + p + '&b=' + b + '&l=' + l + '&a=' + a + '&ob=' + order_by + '&query=' + encodeURI(query) + '&d=' + order_dir_index,{asynchronous:true, evalScripts:true, onComplete:updateOrderImg}); return false;
}

function setWindowPosition(pop_win, parent)
{
    if(parent)
    {
        pos = Position.cumulativeOffset(parent);
        var top_pos;
        if(pos[1] < 700)
        {
            top_pos = "25%";
        }
        else
        {
            top_pos = (-350) + pos[1] + "px";
        }
        pop_win.style.top = top_pos;
        pop_win.style.left = pos[0] + "px";
    }
    else
    {
        pop_win.style.top = add_to_trip_original_x;
        pop_win.style.left = add_to_trip_original_y;
    }
}

function open_create_listing()
{
    Element.hide($("list_errors"));
    if(dialogOverlay) dialogOverlay.hide();
    dialogOverlay = new Dialog.Box('suggest_list1');
    dialogOverlay.show();
}

function save_list(new_list)
{
    var submit_form = check_list_form(new_list);
    var errorDiv = $("list_errors");
    if(submit_form==1 )
    {
        errorDiv.innerHTML = "<span class=\"red\">Please complete all required fields.</span>";
        Element.show(errorDiv);
    }
    else if(submit_form == 2)
    {
        errorDiv.innerHTML = "<span class=\"red\">Invalid Email address.</span>";
        Element.show(errorDiv);
    }
    else
    {
        Element.hide($("list_errors"));
        if(submit_form == 0)
        {
            new Ajax.Request("/listing/suggest",{asynchronous:false, method:'post',
                postBody:'name=' + escape(new_list.elements['name'].value), postBody:'name=' + escape(new_list.elements['name'].value) +
                            '&email=' + escape(new_list.elements['email_address'].value) +
                            '&venue=' + escape(new_list.elements['venue_name'].value) +
                            '&city=' + new_list.elements['city'].value +
                            '&state=' + new_list.elements['state'].value +
                            '&country=' + new_list.elements['country'].value +
                            '&address=' + escape(new_list.elements['address'].value)+
                            '&phone=' + escape(new_list.elements['phone_number'].value) +
                            '&url=' + escape(new_list.elements['url'].value) +
                            '&description=' + escape(new_list.elements['description'].value),onSuccess: function(t) {alert(t.responseText);},
                            on404: function(t) {alert('Server not found!! Please try again');},onFailure: function(t) {alert('Failed error :'+t.status);}});
            Element.hide($('suggest_list1'));
            clear_and_close(new_list, null);
        }
        
    }
    
}
function check_list_form(new_list)
{   
    if((trim(new_list.elements['name'].value).length == 0)||
        (trim(new_list.elements['email_address'].value).length == 0)||
        (trim(new_list.elements['city'].value).length == 0)||
        (trim(new_list.elements['state'].value).length == 0)||
        (trim(new_list.elements['venue_name'].value).length == 0)
      )
    {
        return 1;
    }
    else 
    {
        var email = new RegExp(/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i);
        //var phone = new RegExp([0-9])
        if(!new_list.elements['email_address'].value.match(email))
            return 2;
    }
    
  return 0;
}

function show_trips()
{
    if($('trips').getStyle('display')=="none")
    {
        $('trips').show();
        $('chevron-img').src="/images/MyTrips_X.gif";
    }
    else 
    {
        $('chevron-img').src="/images/MyTrips_Chevron.gif";    
        $('trips').hide();
    }
}

function go_location()
{
	if($('option').value!=0) window.location=$('option').value;
}

function move_ad(holder, temp) {
	var ad_content = $(holder);
	var ad_container = $(temp);
	
	if(ad_content && ad_container) {
		ad_content.appendChild(ad_container);
		ad_container.show();
	}
}

function taggle(id,more){
	if($(id).style.height=="73px"){
		$(id).style.height="100%";
		$(more).innerHTML="Top Categories &uarr;";
	}
	else{
		$(id).style.height="73px";
		$(more).innerHTML="More Categories &darr;";
	}
	//$(id).style.height="60px";
	//alert($(id).style.height);
}

