
var list_action_in_progress = 0;
var list_swap_fav_button_delay_count = 0;
var full_opacity = 0.99999; // Safari doesn't like opacity:1+float
var btn_old;

function list_action(btn,options) {
	if ( !options.list_id && !options.list_name && options.action != "create_list") {
		tag_display_msg('lists_error_msg', 'Please select a list to add to.');
		return;
	}
	if ( options.target_url ) {
		var target_url = options.target_url;
	}
	else {
		var target_url = '/pages/lists/modify_list.php';
	}
	var data = 'action=' + options.action;    
	if ( typeof js_csrf_chk !== 'undefined' ) {
		data = data + '&csrf_chk=' + js_csrf_chk;
	}
	if ( options.skip_my_lists ) { 
		data = data + '&skip_my_lists=true';
	}
	
	//dbug.log('action=' + options.action);
	if ( options.action == "create_list" ) {
		data = data + '&new_list_name=' + encodeURIComponent($(options.new_list_name).value);
		data = data + '&new_list_description=' + encodeURIComponent($(options.new_list_description).value);
		if($('new_lists-actions')) {
			processListBtns($('new_lists-actions'),'hide');
		}
	}
	else {
		if ( options.list_name ) {
			data = data + '&list_name=' + options.list_name;
		}
		if ( options.list_id ) {
			data = data + '&list_id=' + options.list_id;
		}
		if ( options.incl_tracking ) {
			data = data + '&incl_tracking=true';
		}
		if($('edit_lists_add-actions'))
		{
			processListBtns($('edit_lists_add-actions'),'hide');
		}
	}
	if ( options.filter_ref_type ) {
		data = data + '&filter_ref_type=' + options.filter_ref_type;
	}
	if ( options.list_item_description ) {
		data = data + '&list_item_description=' + encodeURIComponent($(options.list_item_description).value);
	}
	if ( options.hide_div_name ) {
		data = data + '&hide_div_name=' + encodeURIComponent(options.hide_div_name);
	}
	if ( options.lists_results_msg_div ) {
		data = data + '&lists_results_msg_div=' + encodeURIComponent(options.lists_results_msg_div);
	}
	if ( options.list_error_msg_div ) {
		data = data + '&lists_error_msg_div=' + encodeURIComponent(options.lists_error_msg_div);
	}
	if ( (options.action == 'del' || options.action == 'del_list') && options.confirm_del ) {
		if ( !confirm('Are you sure you want to remove this item?') ) {
			//dbug.log('Delete confirmed.  Aborting...');
			return;
		}
	}
	if ( ((options.action == 'del') || (options.action == 'del_list')) && options.hide_div_name ) {
		$(options.hide_div_name).setStyle('opacity', 0.5);
	}
	else if (options.action == 'del_list' && options.redirect) {
		data = data + '&redirect=true&redirect_url=' + encodeURIComponent(options.redirect_url);
	}

	// use this format for buttons to store ref_type and ref_id
	// -- format: [button_type]-[ref_type]-[ref_id]
	btn = btn.parentNode;
	//dbug.log('grabbing ref_type and ref_id from %s', $(btn).className);
	// grab ref_type and ref_id from btn
	var btn_selector = extract_btn_selector($(btn).className);
	if ( btn_selector )
	{
		var btn_info = btn_selector.split("-");
		data = data + '&ref_type=' + btn_info[1] + '&ref_id=' + btn_info[2];

		// update fans if using big add to favs button
		if (btn_selector.indexOf('big') > 0) {
			if ( $('fans_body') ) {
				data = data + '&refresh_fans=1';
			}
			else if ( $('fans') ) {
				data = data + '&refresh_fans=true&tab=fans';
			}
		}
	}
	if (supportsAjax()) {
		if ( btn_selector ) {
			if ( btn_selector.indexOf('save') <= 0 && btn_selector.indexOf('del') <= 0 ) {
				//dbug.log('applying affects to list action button %s', btn_selector);
				var btns = $$("." + btn_selector);
				btns.each( function(cur_btn) {
					list_action_in_progress = 1;
					btn_old = $(cur_btn).innerHTML;
					var myEffects = $(cur_btn).effects( {
						onComplete: function () {
							list_action_in_progress = 0;
								if (btn_selector.indexOf('big') > 0) {
									$(cur_btn).setHTML('&nbsp;');
								} else {
									$(cur_btn).setHTML('Processing...');
								}
								$(cur_btn).addClass('processing');
								$(cur_btn).effects().custom({'opacity': [0, full_opacity]});
						}
					} ).custom({'opacity': [1, 0]});
				} );
			}
			data = data + '&btn_selector=' + btn_selector;
		}
		data = data + '&ajax=1';
		//dbug.log('calling ' + target_url + '?' + data + ' via ajax');
		new Ajax(target_url, {postBody : data, method: 'post', onComplete : process_list_action}).request();
		return true;
	}
	else {
		data = data + '&ajax=0';
		document.location = target_url + '?' + data;
	}    
}

function processListBtns(div,action) {
	var btns = div.getElementsByTagName('a');
	var imgs = div.getElementsByTagName('img');
	var btn_display = action == 'hide' ? 'none' : '';
	var img_display = action == 'hide' ? '' : 'none';
	for(var i=0;i<btns.length;i++) {
		$(btns[i]).setStyle('display',btn_display);
	}
	for(var i=0;i<imgs.length;i++) {
		$(imgs[i]).setStyle('display',img_display);
	}
}

function extract_btn_selector(btn_selector) {
	var foundSelector = false;
	if (btn_selector.indexOf(" ") > 0) {
		var btn_selectors = btn_selector.split(" ");
		var foundSelector = false;
		for (var i=0;i<btn_selectors.length;i++) {
			if (btn_selectors[i].indexOf("-") > 0 && btn_selectors[i].split("-").length >= 2) {
				btn_selector = btn_selectors[i];
				foundSelector = true;
				i = btn_selectors.length;
			}
		}
	} else {
		if (btn_selector.indexOf("-") > 0 && btn_selector.split("-").length >= 2) {
			foundSelector = true;
		}
	}
	if (!foundSelector) {
		return false;
	}

	return btn_selector;
}

function list_swap_fav_button(btn_div, list_action_btn) {
	if ($(btn_div)) {
		if ( list_action_in_progress ) {
			list_swap_fav_button_delay_count++;
			// if it takes more than 5 attempts, e.g 5 seconds, move on.
			if ( list_swap_fav_button_delay_count <= 5 )  {
				setTimeout(function(){list_swap_fav_button(btn_div, list_action_btn);}, 500);
			}
			else {
				list_swap_fav_button_delay_count = 0;
				list_action_in_progress = 0;
				var myEffects = $(btn_div).effects( {
					onComplete: function(){
						$(btn_div).setHTML(btn_old);
						if ($(btn_div).className.indexOf(' processing') > 0) {
							$(btn_div).className = $(btn_div).className.slice(0, ($(btn_div).className.indexOf(' processing')+1));
						}
						var myEffects = $(btn_div).effects().custom({'opacity': [0, full_opacity]});
					}
				} ).custom({'opacity': [1, 0]});
			}
			return;
		}
		//dbug.log('bring the div ( %s ) opacity to 0 and then back to 1, then swap in the new div', btn_div.className);
		var myEffects = $(btn_div).effects( {
			onComplete: function() {
				$(btn_div).setHTML(list_action_btn);
				$(btn_div).removeClass('processing');
				if ($(btn_div).className.indexOf(' processing') > 0) {
					$(btn_div).className = $(btn_div).className.slice(0, ($(btn_div).className.indexOf(' processing')+1));
				}
				$(btn_div).effects().custom({'opacity': [0, full_opacity]});
			}
		} ).custom({'opacity': [1, 0]});
	}
}

function process_list_action(results)  {
    if ( results ) {
        // set the data array to be the response of the ajax
        var json_results = eval( '(' + results + ')' );
        //dbug.log('json eval = %O', json_results);
        if ( json_results['error_msg'] ) {
            //dbug.log('Showing error msg: %o', json_results['error_msg']);
						if ( json_results['lists_error_msg_div'] )
						{
							tag_display_msg(json_results['lists_error_msg_div'], json_results['error_msg']);
						}
						else
						{
		          tag_display_msg('lists_error_msg', json_results['error_msg']);
						}
        }

				if ( json_results['btn_selector'] ) {
					var btns = $$("." + json_results['btn_selector']);
					btns.forEach( function(cur_btn) {
						if ($(cur_btn).innerHTML != 'Processing...' || $(cur_btn).innerHTML != '&nbsp;') {
							btn_old = $(cur_btn).innerHTML;
						}
						if ( json_results['error_msg'] ) {
							// if something wrong happened, revert button to previous state
							//dbug.log('error: swapping old %s into %s', btn_old, json_results['btn_selector']);
							list_swap_fav_button(cur_btn, btn_old);
						}
						else
						{
							//dbug.log('swapping %s into %s', json_results['list_action_btn'], json_results['btn_selector']);
							list_swap_fav_button(cur_btn, json_results['list_action_btn']);
						}
					} );
				}
				if ( json_results['fans_module'])
				{
					var fans_module = $('fans');
					if ($(fans_module))
					{
						if (fans_module.innerHTML != json_results['fans_module'])
						{
							//dbug.log('updating fans');
							var myEffects = $(fans_module).effects( {
								onComplete: function() {
									$(fans_module).setHTML(json_results['fans_module']);
									$(fans_module).style.display = json_results['total_fans'] > 0 ? '' : 'none';
									var myEffects = $(fans_module).effects().custom({'opacity': [0, full_opacity]});
								}
							} ).custom({'opacity': [1, 0]});
							var total_fan_elements = $$(".fans_count");
							total_fan_elements.forEach( function(cur_fan_el) {
								var myEffects = $(cur_fan_el).effects( {
									onComplete: function() {
										cur_fan_el.setHTML(json_results['total_fans']);
										var myEffects = $(cur_fan_el).effects().custom({'opacity': [0, full_opacity]});
									}
								} ).custom({'opacity': [1, 0]});
							} );
						}
					}
				}
				if ( json_results['action'] == "add" ) {
						//dbug.log('Set the dw tag to count the useract');
						if ( json_results['dw_url'] ) {
								var dw_url = json_results['dw_url'];
						}
						else {
								var dw_url = 'http://dw.com.com/redir?ltype=&siteid=107&edid=107&ptid=6087&onid=10217&useract=172&destURL=';
						}
						dw_url = dw_url + 'http://dw.com.com/clear/c.gif';
						var clrgif = document.createElement('img');
						clrgif.setAttribute('src', dw_url);
						document.body.appendChild(clrgif);
				}
        if ( json_results['user_favorites_dropdown_tpl'] ) {
            //dbug.log('Update the favorites dropdown');
            if ( $('user_favorites_dropdown') ) {
                $('user_favorites_dropdown').setHTML(json_results['user_favorites_dropdown_tpl']);
            }
        }
        if ( json_results['user_lists_dropdown_tpl'] ) {
            //dbug.log('Update the dropdown with the user\'s lists');
            if ( $('user_lists_dropdown') ) {
                $('user_lists_dropdown').setHTML(json_results['user_lists_dropdown_tpl']);
            }
        }
        if ( json_results['action'] == "create_list" ) {
            if ( json_results['error_msg'] ) {
                $('new_list_name').value = json_results['new_list_name'];
                $('new_list_description').value = json_results['new_list_description'];
            }
            else {
                $('new_list_name').value = '';
                $('new_list_description').value = '';
                $('new_lists').setStyle('display', 'none');
                $('edit_lists_add').setStyle('display', 'block');
            }
						if ($('new_lists-actions')) {
							processListBtns($('new_lists-actions'),'show');
						}
        }
        else if ( ((json_results['action'] == "del") || (json_results['action'] == "del_list")) && json_results['hide_div_name'] && !json_results['error_msg'] ) {
            //dbug.log("hiding div: %s", json_results['hide_div_name']);
            $(json_results['hide_div_name']).setStyle('display', 'none');
        }
				else if (json_results['action'] == "del_list" && json_results['redirect'] && json_results['redirect_url'] && !json_results['error_msg']) {
					if ( json_results['results_msg'] ) {
						//dbug.log('Showing results msg: ' + json_results['results_msg']);
						if ( json_results['lists_results_msg_div'] ) {
							tag_display_msg(json_results['lists_results_msg_div'], json_results['results_msg']);
						}
						else {
							tag_display_msg('lists_results_msg', json_results['results_msg']);
						}
					}
					//dbug.log("delete list successful, redirecting to %s", json_results['redirect_url']);
					window.location = json_results['redirect_url'];
				}
				else {
					if ($('edit_lists_add-actions')) {
						processListBtns($('edit_lists_add-actions'),'show');
					}
				}
        if ( !json_results['error_msg'] && $('edit_lists') ) {
            $('edit_lists').setStyle('display', 'none');
        }
        
        if ( json_results['results_msg'] ) {
            //dbug.log('Showing results msg: ' + json_results['results_msg']);
            if ( json_results['lists_results_msg_div'] ) {
                tag_display_msg(json_results['lists_results_msg_div'], json_results['results_msg']);
            }
            else {
                tag_display_msg('lists_results_msg', json_results['results_msg']);
            }
        }
    }
    else {
        alert('There was an unknown error!');
    }
    
}

function tag_display_msg(div_id, msg) {
	if ( $(div_id) ) {
		//dbug.log('setting div: %s to have msg of: %s', div_id, msg);
		$(div_id).setHTML(msg);
		$(div_id).setStyle('display', 'block');                
		setTimeout(
			function() {
				// this check is in place for the add new items search
				// in case the user closes add new items before the msg div completes the effects
				if ( $(div_id) )
				{
					$(div_id).setStyle('display', 'none');
				}
			}, 5000);
	}
	else {
			//dbug.log('div: %s does not exist.  could not set msg of: %s', div_id, msg);
	}
}

function tag_list(list_id) {
    var target_url = '/pages/lists/tag_list.php';

    var form_name = 'tags-form-'+list_id;
    
    var form = $(form_name);
    
    if (supportsAjax()) {
        new Ajax (target_url, {method: 'post', postBody: $F(form), onComplete: list_process_tag}).request();
        return true;
    }
    else {
        form.ajax.value = 0;
        form.action = target_url;
        form.method = 'POST';
        form.submit();
        return false;
    }
    
}

function list_process_tag(results) {
	var json_results = eval( "(" + results + ")" );
	if ( json_results['success'] ) {
        //dbug.log('Set the dw tag to count the useract');
        if ( json_results['dw_url'] ) {
            var dw_url = json_results['dw_url'];
        }
        else {
            var dw_url = 'http://dw.com.com/redir?ltype=&siteid=107&edid=107&ptid=6087&onid=10217&useract=186&destURL=';
        }
        dw_url = dw_url + 'http://dw.com.com/clear/c.gif';
        var clrgif = document.createElement('img');
        clrgif.setAttribute('src', dw_url);
        document.body.appendChild(clrgif);
	}
	var msg = 'tag-list-success';
	var form = 'tag-list-form';
	var div = 'tag-list';
	if ( json_results['list_id'] ) {
	    msg = msg + '-' + json_results['list_id'];
	    form = form + '-' + json_results['list_id'];
	    div = div + '-' + json_results['list_id'];
	}
	$(msg).setHTML(json_results['msg']);
	$(msg).setStyle('display', 'block');
	setTimeout(function() {
	    $(div).setStyle('display', 'none');
	}, 3000);
	
}

// stoopid IE & mootools
// write my own accordian since IE shows the buttons... ARG!
function show_tagging( div_name ) {
    //dbug.log('calling show_tagging(%s)', div_name);
    var all_div = $$('div.tagging'); 
    //dbug.log('all_div = %o', all_div);
    // loop and close the open divs
    // and open the selected one.  or close if the case calls for it
    all_div.each(function(my_div){
    	if ( my_div.id != div_name ) {
    	    my_div.setStyle('display', 'none');
    	}
    	else {
    	    if ( my_div.getStyle('display') == 'none' ) {
    	        my_div.setStyle('display', 'block');
    	    }
    	    else {
    	        my_div.setStyle('display', 'none');
    	    }
    	}
    });
    
}

function list_search(page_val) {
    var target_url = "/pages/lists/search.php";
    if ( !isNaN(page_val) ) {
        $('edit_list_search_page').value = parseInt(page_val);
    }
    else {
        $('edit_list_search_page').value = 0;
    }
    if (supportsAjax()) {
        if ( $('edit_list_search_results').getStyle('opacity') == '1' || $('edit_list_search_results').getStyle('opacity') == full_opacity ) {
            $('edit_list_search_results').effect('opacity').start(1,0);
        }
				showIndicator();
        $('edit_list_search').send({onComplete: process_list_search_results});
    }
    else {
        alert("We're sorry, but you can only use this search & add feature if your browser supports AJAX");
    }
    
    // always return false since we don't want to the page to change
    return false;
}

function process_list_search_results(results) {
	var json_results = eval( "(" + results + ")" );
	//dbug.log('json_results = %o', json_results);
	hideIndicator();
	$('edit_list_search_results').effect('opacity').start(0,full_opacity);
	if ( json_results['search_results_tpl'] ) {
	    $('edit_list_search_results').setHTML(json_results['search_results_tpl']);
	}
	    
}

function show_paginated_lists(page_val, list_page, list_id) {
    if(typeof list_page == 'undefined') {
        var list_page = 'list_frontdoor';
    }
    
    if(typeof list_id == 'undefined') {
        var list_id = "";
    }
                
    if ( !isNaN(page_val) ) {
        page_val = parseInt(page_val);
    }
    else {
        page_val = 0;
    }
    
    var target_url = document.location;
    
    //if(list_page == 'list_frontdoor') {
    //    var target_url = url + '/pages/profile/lists.php?';
    //}
    //else if(list_page == 'list_items') {
    //    var target_url = url + '/pages/profile/list_items.php?';
    //}
    
    var data = "page="+page_val;
    

    if(list_id) {
        data = data + "&list_id="+list_id;
    }
    
    data = data + "&ajax=1";
    
    //dbug.log("calling "+target_url+data);
    
	if (supportsAjax()) {

		var left_list = $('lists_left')

		var updated_list = new Fx.Styles(left_list);

		updated_list.start({'opacity':[0]}).chain(function(){
			new Ajax (target_url, 
				{
					method: 'post',
					postBody: data,
					update:'lists_left',
					onComplete: function(){
						updated_list.start({'opacity':[1]});
					}
				}).request();
			
			return true;
		});

	
	}else {
	
		data = data + '&ajax=0';
		document.location = target_url + '?' + data;
	}    
	//alert(target_url);

}