/*///////////////////////////////////////////////////////

	Scripting for Musicadium Website
	Coded 16/05/2007 by James Angus - ucantblamem.com
	(C) Copyright Musicadium Pty Ltd 2006

	The code in this file requires MooTools V1.1.x+
	www.mootools.net

///////////////////////////////////////////////////////*/

var artist_quick_clone;

function actionsEqualHeight() {
    var actions_maxheight = 0;

    $$('div.equal').each(function(el) {
        if (el.offsetHeight > actions_maxheight) {
            actions_maxheight = el.offsetHeight;
        }
    });

    $$('div.equal div.wrap div.wrap div.wrap div.wrap').each(function(el) {
        if (window.ie6) {
            el.style.height = (actions_maxheight-20)+'px';
        } else {
            el.style.minHeight = (actions_maxheight)+'px';
        }
    });
};


function sure(msg) {
	var text = "Are you sure?";

	if (msg != '' && msg != undefined) {
		text = msg;
	}

	if(!confirm(text)) {
		return false;
	}
};


function updateArtistSelect() {
	var newOptions;
	new Request.JSON({  
        url: "/members/artists/get_artists/",  
		onComplete: function(response){
			if (response.action=='success') {		
				var newOptions = response.artists;
				$$('.albumartistselect').each(function(el) {
					var el_selected = 0;
					if (el.options.selectedIndex >= 0) el_selected = el.options[el.options.selectedIndex].value;
					el.innerHTML='';
					var new_selected_index = 0;
					if ($('track_name')) {
						var action = new Element('option').setProperties({ 'value': 0 }).set('html', '').injectInside(el);
						el_selected++;
					}
					for (var i=0; i<newOptions.length; i++) {
						var action = new Element('option').setProperties({ 'value': newOptions[i].value }).set('html', newOptions[i].txt);
						if (newOptions[i].value==el_selected) {
							new_selected_index = i;
						}
						action.injectInside(el);
					}
					el.options.selectedIndex = new_selected_index;
			    });
			    if (artist_quick_clone) {
				    var newEl = artist_quick_clone.options.newElement.children;
				    for (var j=0; j<newEl.length; j++) {
				    	if (newEl[j].className=='albumartistselect') {
				    		newEl[j].innerHTML='';
				    		for (var i=0; i<newOptions.length; i++) {
								var action = new Element('option').setProperties({ 'value': newOptions[i].value }).set('html', newOptions[i].txt).injectInside(newEl[j]);
							}
				    	}
				    }
			    }
		    }
		}
	}).get();
};



/**
Class: QuickClone

Overview:
	This class allows you to throw a list of elements at it which will have  +/- buttons added to them which allow the end-user to quickly clone the element (and containing elements)
 */
var QuickClone = new Class({

	elements: [],
	options: {
		newElement: {},
		hideLast: true,
		parentClass: 'parents',
		index: -1
	},

	initialize: function(elements, options){
		this.elements = $$(elements);
		this.setOptions(options);

		if(this.elements.length > 0) {
			var last = this.elements[this.elements.length-1];
			this.options.newElement = last.clone();

			if(this.options.hideLast == true && this.elements.length > 1) {
				last.dispose();
			}

			this.addButtons();
		}
	},

	addButtons: function(){
		this.elements.each(function(el){
			this.addButton(el);
		}, this);
	},

	addButton: function(el){
		var that = this;

		var actions = new Element('span').addClass('actions');
		var actions_list = new Element('ul').injectInside(actions);

		actions_remove = new Element('li').addClass('remove').set('html', '-').addEvent('click', function(e){
			var parent = this.getParent();
			while(!parent.hasClass(that.options.parentClass)) {
				parent = parent.getParent();
			}
			parent.dispose();
		}, that).injectInside(actions_list);

		actions_add = new Element('li').addClass('add').set('html', '+').addEvent('click', function(e){
			var parent = this.getParent();
			while(!parent.hasClass(that.options.parentClass)) {
				parent = parent.getParent();
			}
			// mod to add the new item to the end of the list
			parent = parent.getParent().children[parent.getParent().children.length-1];
			var newElement = that.options.newElement.clone();
			// update indexes if necessary
			newElement.set('html', newElement.innerHTML.replace(/NULL/g, that.options.index--));
			that.addButton(newElement);
			newElement.injectAfter(parent);
		}, that).injectInside(actions_list);

		var clears = $(el).getElements('br.clear', 'br.clearing');
		if(clears.length > 0) {
			var clear = clears[clears.length-1];
			actions.injectBefore(clear);
		} else {
			actions.injectInside(el);
		}
	}

});
QuickClone.implement(new Options);



window.addEvent('domready', function() {

    // Add a class to the body so we know we're enhancing the markup:
    document.getElement('body').addClass('enhanced');


    // Allow for rounded corners on the "actions" boxes:
    $$('div.box').each(function(el) {
        var wrap = new Element('div').addClass('wrap');
        var wrap2 = wrap.clone();
        var wrap3 = wrap.clone();
        var wrap4 = wrap.clone();
        wrap4.set('html', el.innerHTML).injectInside(wrap3);
        wrap3.injectInside(wrap2)
        wrap2.injectInside(wrap);
        el.innerHTML = '';
        wrap.injectInside(el);
    });

    // Make "actions" boxes equal height:
    actionsEqualHeight();

    // Add "M" to the footer:
    if (document.getElement('#footer div.container')) {
    	var _m = new Element('div').addClass('m').injectInside(document.getElement('#footer div.container'));
    }

    // Wrap input's for rounded corners:
/*
 *  Remember there was an issue with box and potentially a really large html file.
 */
    $$('p.input select', '.input input').each(function(el) {
        var wrap = new Element('div').addClass('w');
        var wrap2 = wrap.clone();
        var wrap3 = wrap.clone();
        var wrap4 = wrap.clone();
        var newel = el.clone();
        newel.injectInside(wrap4);
        wrap4.injectInside(wrap3);
        wrap3.injectInside(wrap2);
        wrap2.injectInside(wrap);
        wrap.injectAfter(el);
        el.parentNode.removeChild(el);
    });

    // Wrap textarea's for rounded corners
    $$('p.textarea textarea').each(function(el) {
        var wrap = new Element('div').addClass('w');
        var wrap2 = wrap.clone();
        var wrap3 = wrap.clone();
        var wrap4 = wrap.clone();
        var newel = el.clone();
        newel.injectInside(wrap4);
        wrap4.injectInside(wrap3);
        wrap3.injectInside(wrap2);
        wrap2.injectInside(wrap);
        wrap.injectAfter(el);
        el.parentNode.removeChild(el);
    });

    $$('ul.buttons a').each(function(el) {
        var inner = el.innerHTML;
        var span = new Element('span').set('html', inner);
        el.set('html', '');
        span.injectInside(el);
    });

    $$('input.genre_outlets').each(function(el) {
        var display_box = el.id.replace('genre_outlet_', 'outlet_genres_');

        if (el.checked) {
            if ($(display_box)) {
               $(display_box).style.display = 'block';
            }
        }

        el.addEvent('click', function(e) {
            //var display_box = this.id.replace('genre_outlet_', 'outlet_genres_');

            if (this.checked) {
                if ($(display_box)) {
                   $(display_box).style.display = 'block';
                }
            }
            else if ($(display_box)) {
               $(display_box).style.display = 'none';
            }
        });
    });

    $$('a.delete').each(function(el) {
    	el.addEvent('click', function(e) {
    		if (!confirm('Are you sure?')) {
    			new Event(e).stop();
    		}
    	});
    });

    if ($('album_upc_code')) {
    	$('album_upc_code').addEvent('focus', function() {
    		$('album_upc_1').checked = 'checked';
    	});
    }

    if ($('user_name')) {
    	$('user_name').focus();
    }

    // Add actions to "Jump Menu's"
    $$('select.jumpmenu').each(function(el) {
    	el.addEvent('change', function(e) {
    		var val = this.options[this.selectedIndex].value;
    		if (val != undefined && val != '') {
    			window.location.href = val;
    		}
    	});
    });
    
    // add actions to quick_selects
    $$('select.quickselect').each(function(el) {
    	el.addEvent('change', function(e) {
    		var val = this.options[this.selectedIndex].value;
    		if (val != undefined && val != '') {
    			if ($('quickselectform')) {
    				$('quickselectform').submit();
    			}
    		}
    	});
    });

	$$('#usermenu ul li').each(function(el){
		el.addEvent('mouseover', function(e){
			el.addClass('hover');
		}, el);

		el.addEvent('mouseout', function(e){
			el.removeClass('hover');
		}, el);
	});

	// Pay Me Now calculations:
	if ($('paymenow_transfer')) {
		$('paymenow_transfer').addEvents({
			'keyup': function(e){
				var total = parseFloat($('paymenow_total').value).toFixed(2);
				if (isNaN($('paymenow_transfer').value) || $('paymenow_transfer').value=='') {
					$('paymenow_transfer').value = total;
				}
				var value_precision_split = $('paymenow_transfer').value.split('.');
				if (value_precision_split.length > 1) {
					var value_precision = value_precision_split[1];
					$('paymenow_transfer').value = value_precision_split[0] + '.' + value_precision;
				}

				value_precision_split = $('paymenow_transfer').value.split('.');
				if (value_precision_split.length > 1 && value_precision_split[1].length > 2) {
					value_precision = value_precision_split[1].substr(0, 2);
					$('paymenow_transfer').value = (value_precision_split[0] + '.' + value_precision);
				}

				var value = parseFloat($('paymenow_transfer').value).toFixed(2);
				if (value < 0) {
					value=value*-1;
					$('paymenow_transfer').value=value;
				}
				var available = (total - value).toFixed(2);
				if (available < 0) {
					available = (0).toFixed(2);
					$('paymenow_transfer').value=total;
				}
				$('paymenow_available').innerHTML = available;
			},

			'focus': function(e){
				this.fireEvent('keyup', e);
			},

			'blur': function(e){
				this.fireEvent('keyup', e);
			}
		});
	}

	// Enable user to quickly add multiple prices to the products-edit page:
	if($('product_edit_prices')) {
		quick_clone = new QuickClone($$('#product_edit_prices p.prices'), { parentClass: 'prices' });
	}

	// Enable user to quickly add multiple prices to the coupons-edit page:
	if($('coupon_edit_values')) {
		quick_clone = new QuickClone($$('#coupon_edit_values p.coupons'), { parentClass: 'coupons' });
	}
	
	// Enable the user to quickly add multiple album artist to the Album Step 1 page:
	if ($('quick_album_artists')) {
		artist_quick_clone = new QuickClone($$('#quick_album_artists p.quick_album_artist'), { parentClass: 'quick_album_artist' });
	}
	
	// Enable the user to quickly add multiple album artist to the Album Step 2 page:
	if ($('quick_track_artists')) {
		artist_quick_clone = new QuickClone($$('#quick_track_artists p.quick_track_artist'), { parentClass: 'quick_track_artist' });
	}
	
	SqueezeBox.assign($$('a.squeezebox'), {
		handler: 'iframe',
		size: {x:800, y:500},
		iframeUrlSuffix: '/0/layout/none',
		onClose: function() {updateArtistSelect();}
	});
		

	// How did you hear about us?
	//how_did_you_find_us_other
	if ($('how_did_you_find_us') && $('how_did_you_find_us_other')) {
		var hdyfu = $('how_did_you_find_us');
		var hdyfuo = $('how_did_you_find_us_other_container');
		hdyfuo.fx = new Fx.Slide(hdyfuo, { duration: 500 });
		hdyfuo.fx.hide();
		hdyfu.addEvent('change', function(e){
			if (hdyfu.options[hdyfu.selectedIndex].value.toLowerCase() == 'other') {
				hdyfuo.fx.slideIn();
			} else {
				hdyfuo.fx.slideOut();
			}
		}, hdyfuo);
	}
   	
   	// legal agreement options
    if ($('legals_type_2')) {
    	$('legals_type_2').addEvent('click', function() {
    	    if ($('legals_type_2').checked) {
    			$('legals_type_1').disabled = 'disabled';
    			$('label_legals_type_1').style.color = '#666666';
			} else {
    			$('legals_type_1').disabled = '';
    			$('label_legals_type_1').style.color = '#000000';
			}
    	});
    	if ($('legals_type_2').checked) {
			$('legals_type_1').disabled = 'disabled';
			$('label_legals_type_1').style.color = '#666666';
		}
    }

    if ($('legals_type_1')) {
    	$('legals_type_1').addEvent('click', function() {
    	    if ($('legals_type_1').checked) {
    			$('legals_type_2').disabled = 'disabled';
    			$('label_legals_type_2').style.color = '#666666';
			} else {
    			$('legals_type_2').disabled = '';
    			$('label_legals_type_2').style.color = '#000000';
			}
    	});
    	if ($('legals_type_1').checked) {
			$('legals_type_2').disabled = 'disabled';
			$('label_legals_type_2').style.color = '#666666';
		}
    }
    
    // add function to track upload radio buttons to turn on and off the file and artwork upload fields
	
	$$('input.track_upload').each(function(el) {

        el.addEvent('click', function(e) {
        	// hide the fields
        	$('track_file_upload').style.display='none';
        	$('track_artwork_upload').style.display='none';
        	$('track_artwork_desc').style.display='none';
        	// see if checked and needed to process
            if (el.checked) {
            	// determine what to do
            	switch (el.id) {
            		case 'video_all':
            			// show both track and artwork upload
						$('track_file_upload').style.display='block';
						$('track_artwork_upload').style.display='block';
						$('track_artwork_desc').style.display='block';
            			break;
        			case 'video_artwork':
        				// show just artwork because not allowed to upload tracks
        				$('track_artwork_upload').style.display='block';
        				$('track_artwork_desc').style.display='block';
        				break;
    				case 'audio':
    					// show just track upload because audio
    					$('track_file_upload').style.display='block';
    					break;
				}
            }
        });
        
        // if this input is check then force click to display fields
        if (el.checked) el.click();
    });

});



window.addEvent('resize', function() {
     if (!window.ie7) {
         actionsEqualHeight();
     }
});

