////////////////////////////////
// 	RadarSync JS Utils
// 	Nathan Rapheld
//  nathan@rapheld.com
//  Created 2/25/09


////////////////////////////////
// Utility Functions
jQuery.noConflict();
$j = jQuery;

var DEFAULT_SEARCH_VALUE = "Search";
var FLIPBOX_SPEED = seconds(1000);
var DRAWER_SPEED = seconds(.4);
var SHARE_IT_DEFAULT_MESSAGE = "I thought you might like this download. It's from Packzoola, a new service that helps you discover, download, and backup cool software.";
var shared_strings = { public: "Public", private: "Private" };
var Flash = {};
var FormData;
var flipbox_timer;
var editing_active = false;

var Helptext = {
		search:			{ message: "<p>Narrow your search by activating one or more buttons below.</p><p>Want to browse a category? Simply activate a button below and click Go.<br/>A search term is not required.</p>",
						width: 180 },
		remove_ad:		{ message: "Remove ads from this site for only $9/year"},
		pack_it:    	{ message: "Packs are collections of software. Here, you can add (&quot;pack&quot;) a software title into a new or existing pack. Use Packs to organize, backup, and quickly download your favorite software.",
						width: '180'},
		share_it:		{ message: "To share a pack or item with more than one person, enter multiple emails separated by a comma"},
		login:			{ message: "Login to create software packs with Packzoola and to be a part of the huge RadarSync network of software enthusiasts. If you do not yet have an account, registration is free."},
		industry:		{ message: "The more you share, the more useful our Packzoola community will be! Sharing your industry helps you connect to like-minded people"},
		credit:			{ message: "Was the pack inspired by someone else like a magazine article, blog, or colleague? You can give them credit here."},
		trackers:		{ message: "Trackers are members who follow the changes you make to a pack"},
		show_packs:     { message: "Find out what people who like this software are also using."},
		download:       { message: "Download this item, or scroll down and check out its competitors and more recommendations."},
		copy_pack:      { message: "Click here to make a copy of this Pack and save it to your account. Then go to your My Packs page to view and edit, or download it using PC Updater."},
		search_soft:    { message: "View Competitors or Packs related to your search term by activating a button below. <p></p> Or, see what other people are using: activate a button to Browse Most Packed items by category."},
		empty_pack:		{ message: "Click on the arrow to name and describe your Pack. To add items, search or browse the site."},
		show_similar_packs: { message: "Let us introduce you to new software you'll love!  Get recommendations from Packzoola and find out what people with similar interests are using."}
};

var conf =    
{   
    APIKey: '2_Jn1EuGCQ-vTvy224FWXXh6lHjM31bgOu6biCEBmhfWEg1CE172XkHSLNl0blTmCp'  
};


Function.prototype.bind = function(obj) {
    var method = this;
    temp = function() {
        method.apply(obj, arguments);
    }
    return temp;
}

$j.fn.clear_form = function() {
    return this.each(function() {
        var type = this.type, tag = this.tagName.toLowerCase(), is_multi_select = this.hasAttribute('multiple');
        if (tag == 'form')
            return $j(':input', this).clear_form();
        if (type == 'text' || type == 'password' || tag == 'textarea')
            this.value = '';
        else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = is_multi_select ? -1 : 0;
    });
};

$j.fn.get_form_data = function() {
    FormData = '';
    this.each(function() {
        var type = this.type, tag = this.tagName.toLowerCase(), id = this.id, val = this.value;
        if (tag == 'form')
            return $j(':input', this).get_form_data();

        if (type == 'checkbox' && !this.checked)
            val = 'off';
        else if (type == 'radio' && !this.checked) {
            val = '';
        }

        if (type == 'select-multiple' || type == "select-one") {
            val = [];
            var option, i = 0;
            while ((option = this.options[i++]) != null) {
                if (option.selected) {
                    var attr = option.getAttributeNode("value");
                    var option_value = (attr && attr.specified) ? option.getAttribute("value") : null;
                    if (option_value === null || type == 'select-multiple') option_value = option.text;
                    
                    val[val.length] = option_value.replace("&","_") ;
                }
            }
        }

        if (FormData.length == 0)
            FormData = id + '=' + val;
        else
            FormData += '&' + id + '=' + val;
    });
    return FormData;
};

$j.fn.get_selected = function() {
    var list = '';
    this.each(function() {
        if ($j(this).hasClass('on')) {
            if (list.length > 0)
                list += ',';

            list += this.id;
        }
    });
    return list;
};

$j.fn.exists = function() {
    return this.length > 0;
};

$j.fn.isHidden = function() {
    return this.css('display') == "none"
}

$j.fn.toggle_fade = function() {
    if (this.isHidden()) {
        this.fadeIn(DRAWER_SPEED);
    } else {
        this.hide();
    }
}

function set_all_search_elements (default_value) {
	$j('.search_element:text').each( function() { reset_search(this, default_value); } );
}

function set_initial_modal_position(modal) {
    var height = modal.height() + 100;
    modal.css('top', "-" + height + "px");
}

function css_to_hide_modal(modal) {
    return "-" + (modal.height() + 10) + "px";
}

////////////////////////////////
// Initialization
$j(function(){
	
	set_all_search_elements(DEFAULT_SEARCH_VALUE);
	set_initial_modal_position($j('#pack_it'));
	set_initial_modal_position($j('#login'));
	if ($j('.sortable').length < 2) { $j('#sort_direction').hide();	}
	if ($j('.flipbox').exists()) { flipbox_timer = setInterval(next_flipbox, FLIPBOX_SPEED); }
	
	// Bind initial event handlers
	$j('.search_element:text').livequery('blur', search_blurred);
	$j('.search_element:text').livequery('focus', search_focused);
	$j('#site_search .search_element.submit').livequery('click', site_search_requested);
	
	$j('#login_open').livequery('click', open_login);
	$j('#login_submit').livequery('click', submit_login);
	$j('#login_cancel').livequery('click', close_login);
	
	$j('#social_submit').livequery('click', submit_social);
	$j('#social_cancel').livequery('click', close_social);
	
	$j('.select_profile').livequery('click', select_profile);
	$j('#select_profile').livequery('click', select_profile);
	$j('#load_profile').livequery('click', load_profile);
	
	$j('#software_search .search_element.submit').livequery('click', software_search_requested);
	$j('#software_search .reset').livequery('click', reset_software_search);
	$j('#software_search .switch').livequery('click', manage_switch);
	$j('#software_search .simple_switch').livequery('click', manage_simple_switch);
	$j('.switch_group a').livequery('click', manage_all_switches);
	$j('.simple_switch_group a').livequery('click', manage_all_simple_switches);
	
	$j('#software_search .drawer_handle').livequery('click', toggle_drawer); // specific to software search until toggle_drawer is updated
	$j('#sort_direction').livequery('click', toggle_sort_direction);
	
	$j('.pagination li').livequery('click', select_flipbox_page);
	$j('.flipbox .flip_content').livequery('mouseover', pause_flipbox);
	$j('.flipbox .flip_content').livequery('mouseout', play_flipbox);
	
	$j('.pack_it').livequery('click', pack_it);
	$j('#add_to_pack').livequery('click', add_to_pack);
    $j('#add_to_pack_and_post').livequery('click', add_to_pack_and_post);

	$j('#cancel_pack_it').livequery('click', close_pack_it);
	$j('#select_pack').livequery('change', display_name_new_pack);
	
	$j('#my_packs .drawer_handle').livequery('click', my_packs_toggle_drawer); // specific to my_packs until toggle_drawer is updated
	$j('#my_packs .pack').livequery('mouseover', highlight_row);
	$j('#my_packs .pack').livequery('mouseout', unhighlight_row);
	$j('#my_packs .pack_item').livequery('mouseover', highlight_item_row);
	$j('#my_packs .pack_item').livequery('mouseout', unhighlight_item_row);
	$j('#my_packs .cabinet .edit_tool').livequery('click', edit_pack);
	$j('#pack_editor input[name="pack_shared"]').livequery('change', update_public_pack_count);
	$j('#my_packs .cabinet .delete_tool').livequery('click', delete_pack);
	$j('#pack_editor #cancel_pack_editor').livequery('click', cancel_pack_editor);
	$j('#pack_editor #submit_pack_editor').livequery('click', submit_pack_editor);
	$j('#my_packs .pack_items .edit_tool').livequery('click', edit_item);
	$j('#my_packs .pack_items .delete_tool').livequery('click', delete_item);
	$j('#my_packs #cancel_item_editor').livequery('click', close_item_editor);
	$j('#my_packs #submit_item_editor').livequery('click', submit_item_editor);
	$j('#my_packs #add_new_pack').livequery('click', add_pack);
	
	$j('#my_packs .email_tool').livequery('click', my_packs_share_it);
	$j('#share_it #cancel_share_it').livequery('click', close_share_it);
	$j('#share_it #submit_share_it').livequery('click', submit_share_it);
	
	$j('.pack.item_detail .email_tool').livequery('click', pack_detail_share_it);
	$j('#download_pack').livequery('click', download_pack);
	
	//////////////////////////////////////
	// The Flash object holds the list of flash message
	// JQuery objects used to communicate feedback to the user
	Flash = {
			main:			$j('#main .message').eq(0),
			pack_it:		$j('#pack_it .message'),
			share_it:		$j('#share_it .message'),
			login:			$j('#login .message'),
			social:			$j('#social .message'),
			pack_editor:	$j('#pack_editor .message')
	};
});

function download_pack() {
    if (confirm("Open and download this Pack from your 'My Packs' folder on RadarSync's PC Updater.\r\nIf you don't have it, click OK to download.")) {
		location="http://www.radarsync.com/installers/radarsync.exe"
	}
}

function highlight_row() {
    if (!editing_active) {
        $j(this).css('background-color', "white");
    }
}

function unhighlight_row() {
    if (!editing_active) {
        $j(this).css('background-color', "transparent");
    }
}

function highlight_item_row() {
    if (!editing_active && !parent_item_element(this).find('.tools').is(":visible")) {
        parent_item_element(this).find('.tools').show();
        highlight_row.call(parent_item_element(this));
    }
}

function unhighlight_item_row() {
    if (!editing_active) {
        parent_item_element(this).find('.tools').hide();
        unhighlight_row.call(parent_item_element(this));
    }
}

function edit_item() {
    var item_notes = parent_item_element(this).find('.item_notes');
    editing_active = true;
    hide_item_tools();

    var notes_string = item_notes.text();
    $j('#item_editor #item_editor_notes').val(notes_string);

    $j('#item_editor').insertAfter(item_notes);
    item_notes.hide();
    $j('#item_editor').toggle_fade();
}

function close_item_editor() {
    editing_active = false;
    unhighlight_item_row.call(this);

    parent_item_element(this).find('.item_notes').toggle_fade();
    $j('#item_editor').insertAfter('body').hide();
}

function submit_item_editor() {
    var pack = parent_pack_element(this);
    var pack_element_id = pack.attr('id');
    var pack_id = pack_element_id.replace('packkey', '');
    var item = parent_item_element(this);
    var item_element_id = item.attr('id');
    var item_id = item_element_id.replace('itemkey', '');
    var notes = $j('#item_editor #item_editor_notes').val();

    $j.ajax({
        type: 'POST',
        url: 'http://' + window.location.host + '/PacksHandler.aspx',
        data: 'pack_handler=1&handler_action=update_pack_item&pack_id=' + pack_id + '&item_id=' + item_id + '&notes=' + notes,
        dataType: 'text',
        beforeSend: function() {
        },
        success: function(results) {
            if (results) {
                parent_item_element(this).find('.item_notes').html(notes);
                close_item_editor.call(this);
            }
            else
                display_flash_message('Item details not saved, please try again later');
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            display_flash_message('Error: ' + textStatus);
        },
        complete: function() {
        }
    });
    
    parent_item_element(this).find('.item_notes').html(notes);    
    close_item_editor.call(this);
}

function delete_item() {
    var pack = parent_pack_element(this);
    var pack_element_id = pack.attr('id');
    var pack_id = pack_element_id.replace('packkey', '');
    var item = parent_item_element(this);
    var item_element_id = item.attr('id');
    var item_id = item_element_id.replace('itemkey', '');
    var item_count = get_pack_item_count.call(item);
    var pack_name = pack.find('.name').text();
    var item_name = item.find('.item_name').text();
    
    if (confirm("Remove " + item_name + " from " + pack_name + "?")) {
        toggle_spinner(pack.find('.item_count'));
        $j.ajax({
            type: 'POST',
            url: 'http://' + window.location.host + '/PacksHandler.aspx',
            data: 'pack_handler=1&handler_action=remove_item&pack_id=' + pack_id + '&item_id=' + item_id,
            dataType: 'text',
            beforeSend: function() {
            },
            success: function(results) {
                if (results) {
                    item.fadeOut(DRAWER_SPEED, function() {
                        item.parent().remove();
                        pack.find('.item_count').text(item_count - 1);
                        if (!$j('.pack_item').exists())
                            $j('#no_items').show();
                        
                        display_flash_message("The item " + item_name + " has been removed from " + pack_name);
                    });
                }
                else
                    display_flash_message('Failed to remove item ' + item_name + ', please try again later');
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                display_flash_message('Error: ' + textStatus);
            },
            complete: function() {
            }
        });
    }
}

function get_pack_item_count() {
    return $j(this).closest('.pack_items').find('.pack_item').length;
}

function get_total_pack_count() {
    return Number($j('#total_pack_count').text());
}

function get_public_pack_count() {
    return Number($j('#public_pack_count').text());
}

function set_total_pack_count(new_count) {
    $j('#total_pack_count').text(new_count);
}

function set_public_pack_count(new_count) {
    $j('#public_pack_count').text(new_count);
}

function update_public_pack_count() {
    var current_count = get_public_pack_count();
    var shared_string = $j(this).val();
    shared_string.toLowerCase() == 'y' ? current_count++ : current_count--;
    set_public_pack_count(current_count);
}

function add_pack() {
    var sort_ids = [];
    $j('.sortable').each(function(i, el) {
        $j(el).find('.cabinet').removeClass('first');
        sort_ids.push(el.id);
    });
    
    try{
        var highest_sort_id = sort_ids.sort().pop();
        var next_sort_number = Number(highest_sort_id.match(/\d+/)[0]) + 1;
    }
    catch(err)
    {
        next_sort_number = 0;
    }
    var new_pack = $j('#new_pack').clone();
    new_pack.attr('id', "sort" + next_sort_number);

    $j.ajax({
        type: 'POST',
        url: 'http://' + window.location.host + '/PacksHandler.aspx',
        data: 'pack_handler=1&handler_action=new_pack',
        dataType: 'text',
        beforeSend: function() {
        },
        success: function(results) {
            new_pack.find('.pack').attr('id', "packkey" + results);
            new_pack.addClass("sortable");
            new_pack.insertAfter('#no_packs');
            set_total_pack_count(get_total_pack_count() + 1);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            display_flash_message('Error: ' + textStatus);
        },
        complete: function() {
        }
    });
}

function delete_pack() {
    var pack = parent_pack_element(this);
    var pack_element_id = pack.attr('id');
    var pack_id = pack_element_id.replace('packkey', '');
    var name = pack.find('.name').text();

    if (confirm("Delete " + name + "?")) {
        toggle_spinner(pack.find('.tools'));
        set_total_pack_count(get_total_pack_count() - 1);
        if (pack.find('.sharing').text() == shared_strings['public']) {
            set_public_pack_count(get_public_pack_count() - 1);
        }
        
        $j.ajax({
            type: 'POST',
            url: 'http://' + window.location.host + '/PacksHandler.aspx',
            data: 'pack_handler=1&handler_action=delete_pack&pack_id=' + pack_id,
            dataType: 'text',
            beforeSend: function() {
            },
            success: function(results) {
                if (results) {
                    pack.fadeOut(DRAWER_SPEED, function() {
                        pack.parent().remove();
                        $j('#pack_it #select_pack option[value="' + pack_element_id + '"]').remove();
                        if ($j('.pack').length == 1)
                            $j('#sort_direction').hide();
                        if (!$j('.pack').exists())
                            $j('#no_packs').show();

                        display_flash_message("The pack " + name + " has been deleted");
                    });
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                display_flash_message('Error: ' + textStatus);
            },
            complete: function() {
            }
        });
    }
}

function edit_pack() {
    var pack = parent_pack_element(this);
    var drawer_handle = parent_pack_element(this).find('.drawer_handle');
    var drawer = parent_pack_element(this).find('.drawer');
    var all_drawer_handles = $j('.drawer_handle');
    editing_active = true;

    toggle_pack_tools.call(this);
    clear_flash_messages();

    populate_pack_editor.call(this);
    swap_in_pack_editor.call(this);
}

function cancel_pack_editor() {
    clear_flash_messages();
    close_edit_pack.call(this);
}

function close_edit_pack() {
    editing_active = false;
    toggle_pack_tools.call(this);
    unhighlight_row.call(parent_pack_element(this).find('.cabinet'));
    swap_out_pack_editor.call(parent_pack_element(this));
}

function submit_pack_editor() {
    //add spinner for AJAX
    if (save_pack_metadata.call(this)) {
        var pack = parent_pack_element(this);
        var pack_element_id = pack.attr('id');
        var pack_id = pack_element_id.replace('packkey', '');
        
        var that = this;
        var close_edit_pack_callback = function() {
        	close_edit_pack.call(that);
        }

        $j.ajax({
            type: 'POST',
            url: 'http://' + window.location.host + '/PacksHandler.aspx',
            data: $j('#pack_editor_form').get_form_data() + '&pack_handler=1&handler_action=save_pack&pack_id=' + pack_id,
            dataType: 'json',
            beforeSend: function() {
            },
            success: function(results) {
                if (results.Errors.length == 0) {
                    close_edit_pack_callback();
                    display_flash_message("Pack updated");
                    
                }
                else {
                    var err = '';
                    for (var i = 0; i < results.Errors.length; i++) {
                        err += '<li>' + results.Errors[i].ErrorText + '</li>';
                    }
                    display_flash_message('Please correct the following:<ul>&nbsp;</ul><ul style="font-weight:normal">' + err + '</ul>');
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                display_flash_message('Error: ' + textStatus, Flash.pack_it);
            },
            complete: function() {
                

            }
        });
    }
}

function populate_pack_editor() {
    $j('#pack_editor form').clear_form();

    var name = parent_pack_element(this).find('.name').text();
    $j('#pack_editor #pack_name').val(name);

    var shared_string = parent_pack_element(this).find('.sharing').text();
    var index = (shared_string == shared_strings['public']) ? 0 : 1;
    $j('#pack_editor :radio[name="pack_shared"]').eq(index).attr('checked', 'checked');

    var categories = [];
    parent_pack_element(this).find('.pack_topics li').each(function(i) { categories[i] = $j(this).text(); });

    
    
    $j('#pack_editor select option:selected').each(function() { $j(this).attr("selected", ""); });
    for (var i = 0; i < categories.length; i++) {
        $j('#pack_editor #pack_topics option:contains("' + categories[i] + '")').attr('selected', 'selected');
    }

    var description = parent_pack_element(this).find('.description').text();
    $j('#pack_editor #pack_description').val(description);

    var pack_credit = parent_pack_element(this).find('.credit a').text();
    $j('#pack_editor #pack_credit').val(pack_credit);

    var pack_credit_link = parent_pack_element(this).find('.credit a').attr('href');
    $j('#pack_editor #pack_credit_link').val(pack_credit_link);

    
}

function save_pack_metadata() {
    var metadata = {};
    metadata.is_shared = $j('#pack_editor :radio[name="pack_shared"][value="Y"]').attr('checked');
    metadata.name = $j('#pack_editor #pack_name').val();
    metadata.description = $j('#pack_editor #pack_description').val();
    metadata.pack_credit = $j('#pack_editor #pack_credit').val();
    metadata.pack_credit_link = $j('#pack_editor #pack_credit_link').val();
    metadata.tracker_count = parseInt(parent_pack_element(this).find('.tracker_count').text());
    metadata.categories = "";
    $j('#pack_editor select option:selected').each(function() { metadata.categories += "<li>" + this.innerHTML + "</li>\n"; });

    if (validate_pack_metadata(metadata) && confirm_change_to_private_pack(metadata)) {
        var shared_string = metadata.is_shared ? shared_strings['public'] : shared_strings['private'];
        parent_pack_element(this).find('.sharing').html(shared_string);
        parent_pack_element(this).find('.name a').text(metadata.name);
        parent_pack_element(this).find('.pack_topics').html(metadata.categories);
        parent_pack_element(this).find('.description').html(metadata.description);
        parent_pack_element(this).find('.credit a').html(metadata.pack_credit);
        parent_pack_element(this).find('.credit a').attr('href', metadata.pack_credit_link);
        
        if (metadata.is_shared && isNaN(metadata.tracker_count)) {
            parent_pack_element(this).find('.tracker_count').html('0');
            parent_pack_element(this).find('.tracker_count').removeClass('private');
        }
        else if (!metadata.is_shared) {
            parent_pack_element(this).find('.tracker_count').html('');
            parent_pack_element(this).find('.tracker_count').addClass('private');
        }
        
        return true;
    }

    return false;
}

function validate_pack_metadata(metadata) {
    var is_valid = true;
    var message = "Update failed:<br/>";
    if (metadata.name == '') {
        is_valid = false;
        message += "Name is a required field<br/>";
    }
    if (metadata.is_shared && metadata.categories == '') {
        is_valid = false;
        message += "Topics/Professions is a required field for public packs";
    }
    if (!is_valid)
        display_flash_message(message, Flash.pack_editor);

    return is_valid;
}

function confirm_change_to_private_pack(metadata) {
    if (!metadata.is_shared && metadata.tracker_count > 0)
        return confirm("You have " + metadata.tracker_count + " members tracking this pack.\nYou will lose these followers if you make it private.\n\nAre you sure you want to do this?");

    return true;
}

function toggle_pack_tools() {
    parent_pack_element(this).find('.cabinet .tools').toggle();
}

function show_item_tools() {
    parent_pack_element(this).find('.pack_item .tools').show();
}

function hide_item_tools() {
    $j('.pack_items .tools').hide();
}

function swap_in_pack_editor() {
    toggle_visibility_of_drawer_handles();
    parent_pack_element(this).find('.pack_metadata').toggle_fade();
    $j('#pack_editor').prependTo(parent_pack_element(this).find('.drawer'));
    $j('#pack_editor').toggle_fade();
}

function swap_out_pack_editor() {
    toggle_visibility_of_drawer_handles();
    $j('#pack_editor').insertAfter('body');
    $j('#pack_editor').toggle_fade();
    parent_pack_element(this).find('.pack_metadata').toggle_fade();
}

function toggle_visibility_of_drawer_handles() {
    var all_drawer_handles = $j('.drawer_handle');
    if (all_drawer_handles.eq(0).css('visibility') == 'hidden') {
        all_drawer_handles.css('visibility', 'visible');
    } else {
        all_drawer_handles.css('visibility', 'hidden');
    }
}


////////////////////////////////
// Share It! Drawer
function my_packs_share_it() {
	if ($j(this).is_in_pack()) {
		var type = "pack";
		var pack = parent_pack_element(this);
		var name = pack.find('.name').text(); 
		var id = pack.attr('id');
	}
	else {
		var type = "item";
		var item = parent_item_element(this);
		var name = item.find('.item_name').text();
		var id = item.attr('id');
	}
	open_share_it(name, id, type);
}

function pack_detail_share_it() {
	var id = $j(this).attr('id');
	var name = $j('#pack_name').text();
	var type = "pack";
	open_share_it(name, id, type);
}

function open_share_it(name, id, type) {
    $j('#shared_item_name').html(name);
    $j('#share_invite_link').html('<a href="http://' + window.location.host + '/invite/p' + id.replace('packkey','') + '">Invite contacts from your email account.</a>')
    $j('#share_message').val(SHARE_IT_DEFAULT_MESSAGE);
    $j('#share_it_form').append('<input id="id_to_share" type="hidden" name="id_to_share" value="' + id + '"/>');
    $j('#share_it_form').append('<input id="type_to_share" type="hidden" name="type_to_share" value="' + type + '"/>');
    show_shadowbox();
    $j("#share_it").animate({ top: '110px' }, DRAWER_SPEED);
}

function close_share_it(message) {
	$j('#share_it_form #id_to_share').remove();
	$j('#share_it_form #type_to_share').remove();
	$j('#share_it').animate({top: css_to_hide_modal($j('#share_it'))}, DRAWER_SPEED, function() {
			$j('#share_with').val('');
			$j('#share_message').val('');
			hide_shadowbox();
			display_flash_message(message);
		});
}

function submit_share_it() {
    var emails = $j('#share_with').val();
    if (emails == "") {
        display_flash_message("Email required", Flash.share_it);
        return false;
    }

    toggle_spinner(Flash.share_it);
    $j.ajax({
        type: 'POST',
        url: 'http://' + window.location.host + '/PacksHandler.aspx',
        data: $j('#share_it_form').get_form_data() + '&pack_handler=1&handler_action=share',
        dataType: 'text',
        beforeSend: function() {
        },
        success: function(result) {
            close_share_it(result);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            display_flash_message('Error: ' + textStatus, Flash.share_it);
        },
        complete: function() {
            toggle_spinner(Flash.share_it);
        }
    });
}
    
////////////////////////////////
// Login Functions
function open_login() {
    show_shadowbox();
    $j('#login').animate({ top: '110px' }, DRAWER_SPEED);
}

function open_social(pack, item) {
    show_shadowbox();
    $j('#social_pack').val(pack);
    $j('#social_item').val(item);
    social_set_status_text(pack, item);
    $j('#social').animate({ top: '110px' }, DRAWER_SPEED);
}

function submit_social(){
    submit_social_internal();
}
function close_login(message) {
    $j('#login').animate({ top: css_to_hide_modal($j('#login')) }, DRAWER_SPEED, function() {
        hide_shadowbox();
        display_flash_message(message);
        $j('#login_form').clear_form();
        Flash.login.html('');
    });
}

function close_social(message) {
    $j('#social').animate({ top: css_to_hide_modal($j('#social')) }, DRAWER_SPEED, function() {
        hide_shadowbox();
        display_flash_message(message);
        Flash.social.html('');
    });
}

function fb_login() {
    var href = window.location.href;
    var search = window.location.search;
    
    if (search == '')
        search = '?fblogin=true';
    else if (search.indexOf('fblogin=true') == -1)
        search += '&fblogin=true';

    close_login();
    window.location.search = search;
}

function submit_login() {
    var username = $j('#login_username').val();
    var password = $j('#login_password').val();
    var remember = $j('#login_remember').attr("checked");

    toggle_spinner(Flash.login);

    if (username == '' || password == '') {
        $j('#login_password').val('');
        display_flash_message('Please fill in your user name and password', Flash.login);
    }
    else {
        PageMethods.Login(username, password, remember, LoginSucceeded, LoginFailed);
    }
}

function search_text(where, text) {
    if (text != null && text != "") {
        window.location = where + '?txt=' + $j('#software_search_field').val() + '&plt=&tag=&page=1'
    }
}

function LoginSucceeded(result, userContext, methodName) {
    if (methodName == 'Login') {
        if (result != '' && result) {
            toggle_spinner(Flash.login);
            close_login();
            window.location.href = "http://" + window.location.host + "/packs";
        }
        else {
            display_flash_message('Login failed, please try again...', Flash.login);
        }
    }
}

function Logout() {
    $j('#divLoggedIn').hide();
    $j('#divLoggedOut').show();
}

function LoginFailed(error) {
    //display_flash_message('Error: ' + error.get_message());
    display_flash_message('An error has occured... Please try again later', Flash.login);
}

////////////////////////////////
// Search Field Functions
function site_search_requested() {
    var search_field = $j('#site_search_field');
    var query = search_field.val();
    /*
    var default_value = search_field.attr('default_value');
    if (query == "" || query == default_value)
    return false;
    alert("Searching the site for:\n\n" + query);
    return false;
    */
}

function software_search_requested() {
    var search_field = $j('#software_search_field');
    var query = search_field.val()
    /*
    var default_value = search_field.attr('default_value');
    if (query == "" || query == default_value)
    return false;
    alert("Searching the software database for:\n\n" + query);
    return false;
    */
}

function reset_search(target, default_value) {
    $j(target).attr('default_value', default_value);
    $j(target).css("color", "#aaaaaa");
    $j(target).val(default_value);
}

function search_focused() {
    var current_value = $j(this).val();
    var default_value = $j(this).attr("default_value");
    //alert("current value: " + current_value + "\ndefault value: " + default_value);
    if (typeof default_value == "undefined") {
        $j(this).attr("default_value", current_value);
        default_value = current_value;
    }
    if (current_value == default_value) {
        $j(this).css("color", "black");
        $j(this).val("");
    }
}

function search_blurred() {
    if ($j(this).val() == "") {
        var default_value = $j(this).attr('default_value');
        reset_search(this, default_value);
    }
}


////////////////////////////////
// Profile Management Functions
function select_profile() {
    $j('#get_profile').css('visibility', 'visible');
    return false;
}

function load_profile() {
    // demo code...server-side script needed to manage the profile image.
    $j('#profile_image').attr('src', 'assets/images/default_user_photo_loaded.png');
    $j('.leftbox.lb_user_photo .lb_inner').css('border-style', 'solid');
    $j('#get_profile').css('visibility', 'hidden');
    return false;
}


////////////////////////////////
// Software Search
function manage_switch() {
    $j(this).hasClass("on") ? $j(this).removeClass("on") : $j(this).addClass("on");
    send_search(1);
}

function manage_simple_switch() {
    $j('#software_search .simple_switch').removeClass("on");
    $j(this).addClass("on");
    send_search(1);
}

function manage_all_switches() {
    var select_all = $j(this).html().toLowerCase() == 'all'
    var switches = $j(this).parents('.switch_group').find('.switch');
    if (select_all) {
        switches.addClass("on");
    } else {
        switches.removeClass("on");
    }
    send_search(1);
}

function manage_all_simple_switches() {
    var select_all = $j(this).html().toLowerCase() == 'all'
    var switches = $j(this).parents('.simple_switch_group').find('.simple_switch');
    if (select_all) {
        switches.addClass("on");
    } else {
        switches.removeClass("on");
    }
    send_search(1);
}

function reset_software_search() {
    reset_search($j('#software_search_field'), DEFAULT_SEARCH_VALUE);
    $j('#software_search .switch').removeClass("on");
    send_search(1);
}


////////////////////////////////
// Drawer Manager
function toggle_drawer() {
    var active_drawer = '#' + $j(this).attr('value');
    var is_open = $j(this).hasClass('open');
    if (is_open) {
        $j(this).removeClass('open');
        $j(active_drawer).hide();
    } else {
        $j('.drawer_handle').not(this).removeClass('open');
        $j('.tools').not(this).hide();
        $j('.drawer').not(active_drawer).hide();
        $j(this).addClass('open');
        //$j(active_drawer).fadeIn(DRAWER_SPEED); // Fade in don't work correct in Chrome :(
        $j(active_drawer).css("display", "block"); // Fixes bug in Chrome where "display: item-list" fails
    }
    toggle_pack_tools.call(parent_pack_element(this));
}

function my_packs_toggle_drawer() {
    var pack = parent_pack_element(this);
    var this_drawer = pack.find('.drawer');
    var is_open = $j(this).hasClass('open');

    if (is_open) {
        $j(this).removeClass('open');
        this_drawer.hide();
    } else {
        var all_other_drawer_handles = $j('.drawer_handle').not(this);
        var all_other_tools = $j('.tools');
        var all_other_drawers = $j('.drawer').not(this_drawer);

        all_other_drawer_handles.removeClass('open');
        all_other_tools.not(this).hide();
        all_other_drawers.hide();

        $j(this).addClass('open');
        this_drawer.fadeIn(DRAWER_SPEED);
        this_drawer.css("display", "block"); // Fixes bug in Chrome where "display: item-list" fails
    }
    toggle_pack_tools.call(pack);
}

function toggle_sort_direction() {
    var sortables = $j('.sortable');
    var sort_icon = $j('#sort_direction');

    if (sort_icon.hasClass('descend')) {
        sort_icon.attr('src', 'assets/images/sort_ascend.png');
        sort_icon.removeClass('descend');
        sort_icon.addClass('ascend');
    } else {
        sort_icon.attr('src', 'assets/images/sort_descend.png');
        sort_icon.removeClass('ascend');
        sort_icon.addClass('descend');
    }

    reverse_sort_order();
}

function reverse_sort_order() {
    var sortables = $j('.sortable');
    var anchor = sortables.eq(sortables.length - 1);

    var sorter = function() {
        var current = $j(this);
        current.find('.cabinet').removeClass("first");

        if (current.attr('id') == anchor.attr('id')) {
            anchor.find('.cabinet').addClass("first");
            return;
        }

        $j(this).insertAfter(anchor);
    };

    sortables.each(sorter);
}


////////////////////////////////
//Flipbox
function next_flipbox() {
    var current_dot = $j('.pagination li.on');
    var next_dot = current_dot.next();
    current_dot.removeClass("on");
    next_dot = next_dot.length > 0 ? next_dot.addClass("on") : $j('.pagination li:first').addClass("on");
    turn_to_page(current_dot.attr("id"), next_dot.attr("id"))
}

function turn_to_page(from, to) {
    var turn_to = function() {
        $j('#flip' + to).fadeIn(DRAWER_SPEED);
    }
    $j('#flip' + from).fadeOut(DRAWER_SPEED / 4, turn_to);
}

function select_flipbox_page() {
    var current_dot = $j('.pagination li.on');
    var new_dot = $j(this);
    if (current_dot.attr('id') == new_dot.attr('id')) {
        return;
    }
    $j('.pagination li').removeClass("on");
    new_dot.addClass("on");
    turn_to_page(current_dot.attr("id"), new_dot.attr("id"));
    clearInterval(flipbox_timer);
    flipbox_timer = setInterval(next_flipbox, FLIPBOX_SPEED);
}

function pause_flipbox() {
    clearInterval(flipbox_timer);
}

function play_flipbox() {
    flipbox_timer = setInterval(next_flipbox, FLIPBOX_SPEED);
}


////////////////////////////////
// Pack It! Drawer
function open_pack_it(item_name, item_id) {
    $j('#item_name').html(item_name);
    $j('#pack_it_form').append('<input id="item_to_add" type="hidden" name="item_to_add" value="' + item_id + '"/>');
    display_name_new_pack();
    show_shadowbox();
    $j("#pack_it").animate({ top: '110px' }, DRAWER_SPEED);
}

function close_pack_it(message) {
    $j('#pack_it_form input:hidden').remove();
    $j('#pack_it').animate({ top: css_to_hide_modal($j('#pack_it')) }, DRAWER_SPEED, function() {
        if ($j('#select_pack').val() == 'NEW') {
            $j('#select_pack').val('');
        }
        hide_shadowbox();
        display_flash_message(message);
    });
}

function pack_it() {
    $j.ajax({
        type: 'POST',
        url: 'http://' + window.location.host + '/PacksHandler.aspx',
        data: 'pack_handler=1&handler_action=user_packs_list',
        dataType: 'html',
        beforeSend: function() {
            $j('#pack_list').html('');
        },
        success: function(html) {
            $j('#pack_list').html(html);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            display_flash_message('Error: ' + textStatus, Flash.pack_it);
        },
        complete: function() {
        }
    });

    var item_name = $j("#item_name_" + this.id).html(); 	/* This is to get the name on the Search page */
    
    /* Pack Detail & My Packs has a different way of handling the name. Search should be changed to match these pages */
    if (item_name == null) {
    	item_name = $j('#pack_name').text();
    }
    var item_id = this.id;
    open_pack_it(item_name, item_id);
}

function display_name_new_pack() {
    Flash.pack_it.html('');
    if ($j('#select_pack').val() == "NEW") {
        $j('#new_pack_row').show();
        $j('#new_pack_name').focus();
    } else {
        $j('#new_pack_row').hide();
        $j('#new_pack_name').val('');
    }
}

function add_to_pack(post) {
    var message;
    var item_name = $j('#item_name').html();
    var existing_pack = $j('#select_pack').val();
    var new_pack = $j('#new_pack_name').val();

    if (existing_pack == '') {
        display_flash_message("Please select a pack first", Flash.pack_it);
        return false;
    } else if (existing_pack == "NEW" && new_pack == '') {
        display_flash_message("Please provide a name for the new pack", Flash.pack_it);
        return false;
    }

    if (new_pack) {
        message = "Created " + new_pack + " and packed " + item_name + " into it";
    } else {
        message = item_name + " packed";
    }
    
    $j.ajax({
        type: 'POST',
        url: 'http://' + window.location.host + '/PacksHandler.aspx',
        data: $j('#pack_it_form').get_form_data() + '&pack_handler=1&handler_action=pack_item' + '&location=' + window.location,
        dataType: 'json',
        beforeSend: function() {
            toggle_spinner(Flash.pack_it);
        },
        success: function(results) {
            if (results.Errors.length == 0) {
                toggle_spinner(Flash.pack_it);
                close_pack_it(message);
                
                // show invite question
                if (results.NewItemNumber == 3)
                {
                    if (confirm('Congratulations on your new Pack!\n' +  
                                 'Invite your friends to see, download, or comment on it.\n' +
                                 '(You can continue to add to your Pack after the invites are sent)'))
                        location.href = 'http://' + window.location.host + '/invite/p' + existing_pack;
                }
           }
            else {
                display_flash_message(results.Errors[0].ErrorText, Flash.pack_it);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            display_flash_message('Error: ' + textStatus, Flash.pack_it);
        },
        complete: function() {

        }
    });
}

function add_to_pack_and_post() {
    var message;
    var item_name = $j('#item_name').html();
    var existing_pack = $j('#select_pack').val();
    var new_pack = $j('#new_pack_name').val();

    if (existing_pack == '') {
        display_flash_message("Please select a pack first", Flash.pack_it);
        return false;
    } else if (existing_pack == "NEW" && new_pack == '') {
        display_flash_message("Please provide a name for the new pack", Flash.pack_it);
        return false;
    }

    if (new_pack) {
        message = "Created " + new_pack + " and packed " + item_name + " into it";
    } else {
        message = item_name + " packed";
    }
    
    $j.ajax({
        type: 'POST',
        url: 'http://' + window.location.host + '/PacksHandler.aspx',
        data: $j('#pack_it_form').get_form_data() + '&pack_handler=1&handler_action=pack_item' + '&location=' + window.location,
        dataType: 'json',
        beforeSend: function() {
            toggle_spinner(Flash.pack_it);
        },
        success: function(results) {
            if (results.Errors.length == 0) {
                toggle_spinner(Flash.pack_it);
                close_pack_it(message);
                
                // show invite question
                if (results.NewItemNumber == 3)
                {
                    if (confirm('Congratulations on your new Pack!\n' +  
                                 'Invite your friends to see, download, or comment on it.\n' +
                                 '(You can continue to add to your Pack after the invites are sent)'))
                        location.href = 'http://' + window.location.host + '/invite/p' + existing_pack;
                }
                setTimeout('open_social("' + existing_pack + '", "' + item_name + '")', 500);   
            }
            else {
                display_flash_message(results.Errors[0].ErrorText, Flash.pack_it);
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            display_flash_message('Error: ' + textStatus, Flash.pack_it);
        },
        complete: function() {

        }
    });
}

////////////////////////////////
// General
function display_flash_message(message, message_pane) {
    if (message_pane == null) {
        message_pane = Flash.main;
    }
    if (typeof message != "string") {
        message_pane.hide();
        return false;
    }

    message_pane.html(message);
    message_pane.show();
}

function hide_flash_message(message_pane) {
    if (message_pane == null) {
        message_pane = Flash.main;
    }
    message_pane.html('');
    message_pane.hide();
}

function clear_flash_messages() {
    for (message_pane in Flash) {
        Flash[message_pane].hide();
    }
}

function toggle_spinner(message_pane) {
    var spinner = '<img src="http://www.radarsync.com/assets/images/spinner.gif">';
    var message = message_pane.html();
    if (message == spinner) {
        message_pane.html('');
    } else {
        message_pane.html(spinner);
    }
}

function show_shadowbox() {
    if ($j('#shadowbox').length == 0) {
        $j('body').append('<div id="shadowbox"></div>');
    }
    $j('#shadowbox').hide();
    $j('#shadowbox').css("background", "url(assets/images/shadowbox.png) repeat");
    $j('#shadowbox').css("position", "fixed");
    $j('#shadowbox').css("top", "0");
    $j('#shadowbox').css("left", "0");
    $j('#shadowbox').css("width", "5000px");
    $j('#shadowbox').css("height", "5000px");
    $j('#shadowbox').css("z-index", "10");
    //	$j('#shadowbox').fadeIn(300);
    $j('#shadowbox').show();
}

function hide_shadowbox() {
    if ($j('#shadowbox').length > 0) {
        //		$j('#shadowbox').fadeOut(300, function() { $j('#shadowbox').remove(); });
        $j('#shadowbox').remove();
    }
}

function seconds(seconds) {
    return seconds * 1000;
}

function parent_pack_element(child) {
    return $j(child).closest('.pack');
}

function parent_item_element(child) {
    return $j(child).closest('.pack_item');
}

$j.fn.is_in_item = function() {
    return parent_item_element(this).length != 0
}

$j.fn.is_in_pack = function() {
    return parent_item_element(this).length == 0
}
