function toggle_checkbox(id)
{
	element = $(id);
	if (element != null) {
		if(element.checked == false) { 
			element.checked = true;
		} else { 
			element.checked = false;
		}
	}
}

function get_sibling_by_classname(element, classname) {
  found_element = null;
  $A(element.parentNode.childNodes).each(function(item){
    if(item.className == classname) {
      found_element = item;
    }
  });
  return(found_element);
}

function get_fieldsets(container_div) {
	sources = $H()
	$$("#" + container_div + " fieldset").each(function(node){
		sources.set(get_label(node), node);
	});
    return(sources);
}

function get_label(node) {
	label = node.getElementsByTagName('label')[0].innerHTML;
	return(label.substring(0, label.indexOf(':')));
}

function get_input(fieldset) {
	var element = null;
	if (fieldset != null && fieldset.childNodes != null && fieldset.childNodes.length > 0) {
		$A(fieldset.childNodes).each(function(item){
			if (element == null && (item.nodeName == 'SELECT' || item.nodeName == 'INPUT')) {
                element = item;
			}
		});
	}
	return(element);
}

function copy_form_values(source_div, destination_div) {
	destinations = get_fieldsets(destination_div);
    get_fieldsets(source_div).each(function(item){
        source = get_input(item[1]);
		destination = get_input(destinations.get(item[0]));
        if(source != null && destination != null && source.nodeName == destination.nodeName) {
			destination.value = source.value;
		}		
	});
}

function toggle_collapse(link) {
  link = $(link);
  element = get_sibling_by_classname(link, 'collapse_content');
  if (link != null && element != null && element != false) {
		element_display = element.style.display;
		if (element_display == '' || element_display == 'block') {
      toggle_collapse_close(link);
		} else {
      toggle_collapse_open(link);
    }
	}
}

function toggle_collapse_triangle(link, sub, replace) {
  var triangle = null;
  if(link != null) {
    $A(link.childNodes).each(function(item){
      if (triangle == null && item != null && item.nodeName == 'IMG') {
        triangle = item;
      }
    });
  }
  if (triangle != null) {
    triangle.src = triangle.src.sub(sub, replace);
  }
}

function toggle_collapse_open(link) {
  content = get_sibling_by_classname(link, 'collapse_content');
  if (content != null) {
    $(content).show();
  }
  toggle_collapse_triangle(link, 'triangle_closed', 'triangle_open');
}

function toggle_collapse_close(link) {
  content = get_sibling_by_classname(link, 'collapse_content');
  if (content != null) {
    $(content).hide();
  }
  toggle_collapse_triangle(link, 'triangle_open', 'triangle_closed');
}

function collapse_open_all() {
  $A(document.getElementsByClassName("collapse_link")).each(function(item) {
    toggle_collapse_open(item);
  });
}

function collapse_close_all() {
  $A(document.getElementsByClassName("collapse_link")).each(function(item) {
    toggle_collapse_close(item);
  });
}

function enable_form_for_any_class(form_element_id, class_name) {
    var conditional_field = $(form_element_id);
    var any_boxes_checked = false;
    $A(document.getElementsByClassName(class_name)).each(function(item) {
        if (item.checked) {
            any_boxes_checked = true;
        }
    });
    if (any_boxes_checked) {
        conditional_field.disabled = false;
    } else {
        conditional_field.disabled = true;
        conditional_field.selectedIndex = 0;
    }
}

function validate_number(input) {
    validate_number_priv(input, /[^0-9]/, null, null, null);
}

function validate_episode(input) {
    validate_number_priv(input, /[^0-9]/, 2, null, null);
}

function validate_hour12(input) {
    validate_number_priv(input, /[^0-9]/, null, 12, 2);
}

function validate_minute(input) {
    validate_number_priv(input, /[^0-9]/, null, 59, 2);
}


function validate_checked(input) {
    if (input.checked == false){
        show_alert(input);
    } else {
        hide_alert(input);
    }
};

function validate_number_priv(input, banned_values, min_value, max_value, max_chars, alert_id) {
    var cleaned_value = input.value.gsub(banned_values, '');
    if(cleaned_value != input.value) {
        fixed_alert(input, "Numbers only please.");
    } else if(max_chars != null && input.value.length > max_chars) {
        fixed_alert(input, "Please no more than " + max_chars + " digits.");
    } else if(max_value != null && input.value > max_value) {
        fixed_alert(input, "Please enter a number " + max_value + " or less.");
    } else if(min_value != null && input.value != '' && input.value < min_value) {
        fixed_alert(input, "The number of episodes must be at least "+min_value+".");
    } else {
        clear_alert(input);
    }
}

function fixed_alert(form_element, alert_message) {
    var alert_text = get_sibling_by_classname($(form_element), 'temporary_alert');
    if(alert_text != null) {
        alert_text.innerHTML = alert_message;
    }
}

function clear_alert(form_element) {
    fixed_alert($(form_element), '');
}

function show_alert(form_element) {
    var alert_text = get_sibling_by_classname($(form_element), 'temporary_alert');
    alert_text.style.display = "inline";
}

function hide_alert(form_element) {
    var alert_text = get_sibling_by_classname($(form_element), 'temporary_alert');
    alert_text.style.display = "none";
}

function show_removing_rights_alert(form_element) {
    form_element.parentNode.style.backgroundColor = "#FFDB8C";
    update_rights_warning();
}

function hide_removing_rights_alert(form_element) {
    var cellbgcolor = form_element.parentNode.parentNode.bgColor;
    if (cellbgcolor == null) {
        cellbgcolor = "#ffffff";
    }
    form_element.parentNode.style.backgroundColor = cellbgcolor;
    update_rights_warning();
}

function update_rights_warning() {

    var showWarning = false;
    $$('input.validate_checked_rights').each(function(checkbox){
        if(checkbox.checked == false) {
            showWarning = true;
        }
    });

    var rightsWarning = $('removing_rights_warning');
    if (rightsWarning != null) {
        if (showWarning == true) {
            rightsWarning.show();
        } else {
            rightsWarning.hide();
        }
    }
}

// Global array to retain the original onload values of checkboxes with the id 'validate_checked_rights' so they can be validated against.
var validate_checked_original_values = [];

function validate_checked_rights(input) {
   if (validate_checked_original_values != null && validate_checked_original_values.size() > 0) {
       var inputs = $$('input.validate_checked_rights');
       var eindex = inputs.indexOf(input);
       if (validate_checked_original_values[eindex]) {
           if (input.checked == false){
               show_removing_rights_alert(input);
           } else {
               hide_removing_rights_alert(input);
           }
       }
   }
};

function show_removing_rights_alert(form_element) {
   form_element.parentNode.style.backgroundColor = "#FFDB8C";
   var rightsWarning = $('removing_rights_warning');
   if (rightsWarning != null) {
       if(form_element.checked == false) {
           rightsWarning.show();
           if (!$(form_element).hasClassName('warning')) {
               $(form_element).addClassName('warning');
           }
       }
   }
}

function hide_removing_rights_alert(form_element) {
   var rightsWarning = $('removing_rights_warning');
   var cellbgcolor = form_element.parentNode.parentNode.bgColor;
   if (cellbgcolor == null) {
       cellbgcolor = "#ffffff";
   } else if (!Prototype.Browser.IE) {
       cellbgcolor = "#" + cellbgcolor;
   }
   form_element.parentNode.style.backgroundColor = cellbgcolor;
   if ($(form_element).hasClassName('warning')) {
       $(form_element).removeClassName('warning');
   }
   var inputs = $$('input.validate_checked_rights');
   var noWarnings = true;
   inputs.each(function(e) {
       if ($(e).hasClassName('warning')) {
           noWarnings = false;
       }
   });
   if (noWarnings) {
       rightsWarning.hide();
   }
}

/* Behaviour Rules */

var myrules = {
   'div.edittimehourandminutes input.hour12' : function(element){
		element.onkeyup = function(){
     validate_hour12(this);
		}
	},
 'div.edittimehourandminutes input.minute' : function(element){
		element.onkeyup = function(){
     validate_minute(this);
		}
	},
 'a.collapse_link' : function(element){
   element.onclick = function(){
     toggle_collapse(this);
   }
 },
 'input.validate_number' : function(element){
   element.onkeyup = function(){
     validate_number(this);
   }
 },
 'input.validate_episode' : function(element){
   element.onkeyup = function(){
     validate_episode(this);
   }
 },
 'input.validate_checked' : function(element){
   element.onclick = function(){
     validate_checked(this);
   }
 },
 'input.validate_checked_rights' : function(element){
   element.onclick = function(){
     validate_checked_rights(this);
   }
 }
};
Behaviour.register(myrules);

Behaviour.addLoadEvent(function() {
   $$('input.validate_checked').each(function(input){
       if (input.checked == false){
           show_alert(input);
       } else {
           hide_alert(input);
       }
   });
   $$('input.validate_checked_rights').each(function(checkbox){
       validate_checked_original_values.push(checkbox.checked);
   });
});


/* Rights & Pricing Date Format Validation */

var myAlert;

function validate_date(fld) {
    var RegExPattern = /(?=\d)^(?:(?!(?:10\D(?:0?[5-9]|1[0-4])\D(?:1582))|(?:0?9\D(?:0?[3-9]|1[0-3])\D(?:1752)))((?:0?[13578]|1[02])|(?:0?[469]|11)(?!\/31)(?!-31)(?!\/.31)|(?:0?2(?=.?(?:(?:29.(?!000[04]|(?:(?:1[^0-6]|[2468][^048]|[3579][^26])00))(?:(?:(?:\d\d)(?:[02468][048]|[13579][26])(?!\x20BC))|(?:00(?:42|3[0369]|2[147]|1[258]|09)\x20BC))))))|(?:0?2(?=.(?:(?:\d\D)|(?:[01]\d)|(?:2[0-8])))))([\/])(0?[1-9]|[12]\d|3[01])\2(?!0000)((?=(?:00(?:4[0-5]|[0-3]?\d)\x20BC)|(?:\d{4}(?!\x20BC)))\d{4}(?:\x20BC)?)(?:$|(?=\x20\d)\x20))?((?:(?:0?[1-9]|1[012])(?::[0-5]\d){0,2}(?:\x20[aApP][mM]))|(?:[01]\d|2[0-3])(?::[0-5]\d){1,2})?$/;
    if ((fld.value.match(RegExPattern)) && (fld.value!='')) {
        clear_alert(fld);
        myAlert = "no";
    }
    else {
        fixed_alert(fld, " Invalid format.");
        fld.focus();
        myAlert = "yes";
    }
}

function validate_date_alert() {
    //alert (myAlert);
    if (myAlert=="yes") {
        //alert("Invalid format.  Please format using MM/DD/YYYY.");
        return false;
    } else if (myAlert=="no") {
        return true;
    }
}

/* File upload */


function processFileSelection(fileField) {
	if (fileField.id != "additionalScreenshot") {
		// Fill in field
		document.getElementById(fileField.id + "-itemName").innerHTML = fileNameFromPath(fileField.value);
		
		//Display button
		document.getElementById(fileField.id + "Div").style.display = "block";
	}
	else {
		newTitle = document.createElement("h2");
		newTitle.innerHTML = fileNameFromPath(fileField.value);
		
		itemNameContentArea = document.getElementById("additionalScreenshot-itemName");
		itemNames = itemNameContentArea.getElementsByTagName("h2");
		
		if (itemNames.length > 0) {
			for (i=itemNames.length-1; i > -1; i--) {
				if (itemNames[i].getAttribute("class") == "serverGenerated") {
					itemNameContentArea.removeChild(itemNames[i]);
				}
			}
		}
		
		itemNames = itemNameContentArea.getElementsByTagName("h2");

		if (itemNames.length > 0) {
			
			document.getElementById("additionalScreenshot-itemName").insertBefore(newTitle,itemNames[0]);
		}
		else {
			document.getElementById("additionalScreenshot-itemName").appendChild(newTitle);
		}
		
		//Display button
		document.getElementById("additionalScreenshotDiv").style.display = "block";
		
		// Hide file field div
		fileField.parentNode.style.display = "none";
	}
}

function fileNameFromPath(path) {
	if (navigator.userAgent.match(/Windows/)) {
		return path.substring(path.lastIndexOf('\\') + 1, path.length).replace(/%20/g, ' ');
	}
	else {
		return path.substring(path.lastIndexOf('/') + 1, path.length).replace(/%20/g, ' ');
	}
}

/* Toggle Tool Tip */

function toggle_tool_tip (index, index1) {
    close_tool_tips(index);
    close_tool_tips1(index1);
    var div_element = document.getElementsByClassName('div-element')[index];
    div_element.toggle();
}

function close_tool_tips (div_index) {
    var tips = document.getElementsByClassName('div-element');
    for (i=0; i<tips.length; i++) {
        if (i != div_index)
            tips[i].style.display="none";
    }
}

function toggle_tool_tip1 (index1, index) {
    close_tool_tips1(index1);
    close_tool_tips(index);
    var div_element1 = document.getElementsByClassName('div-element1')[index1];
    div_element1.toggle();
}

function close_tool_tips1 (div_index1) {
    var tips1 = document.getElementsByClassName('div-element1');
    for (i=0; i<tips1.length; i++) {
        if (i != div_index1)
            tips1[i].style.display="none";
    }
}

function selectAll(containerClass) {
    $$('.' + containerClass + 'input').each(function(input){
        input.checked=true;
    });
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

//Export Compliance OnLoad Function

Event.observe( window, 'load', function() {
    if ($('stateradio') && $('stateradio').checked) {
        $('hidden-questions').style.display='block';
        $('hidden-upload').style.display='block';
    }
} );

//EULA OnLoad Function

Event.observe( window, 'load', function() {
    if ($('eula-text') && $('eula-text').value) {
        $('row-0').style.display='none';
        $('row-1').style.display='table-row';
        $('row-2').style.display='table-row';
        $('row-3').style.display='table-row';
        $('row-4').style.display='table-row';
    }
} );

// commented ou the uploadFrame hiding until we can get it to stick
function skipUploadCheck(state) {
    var imageDiv = document.getElementById('ApplicationImageSpot');
    if (state) {
        imageDiv.innerHTML = '<img width="57" height="68" src="/images/labelconnect/strikethrough.png">';
        //mwalker - added the visibility lines
        document.getElementById('binaryChooseFile').style.visibility = "hidden";
        document.getElementById('binaryDiv').style.visibility = "hidden";
        document.getElementById('binary-itemName').style.visibility = "hidden";
        
        //$('ApplicationImageSpot').down().src = '/images/labelconnect/strikethrough.png';
        //$('uploadFrame').contentDocument.getElementById('inputframe').style.display = "none";
    } else {
        //mwalker - added the visibility lines
        document.getElementById('binaryChooseFile').style.visibility = "visible";
        document.getElementById('binaryDiv').style.visibility = "visible";
        document.getElementById('binary-itemName').style.visibility = "visible";
        
        if( null == $('binary-itemName') || $('binary-itemName').empty() ) {
            imageDiv.innerHTML = '<img width="57" height="57" src="/images/labelconnect/well.gif">';
            //$('ApplicationImageSpot').down().src = '/images/labelconnect/well.gif';
        }else{
            imageDiv.innerHTML = '<img width="57" height="68" src="/images/labelconnect/check.png">';
            //$('ApplicationImageSpot').down().src = '/images/labelconnect/check.png';
        }
        //$('uploadFrame').contentDocument.getElementById('inputframe').style.display = "block";
    }
}

//Games Ratings onChange Function

Event.observe( window, 'load', function () {

    if ($('primary-category') && $('primary-category').options[$('primary-category').selectedIndex].text == "Games") {
        $('game-ratings').style.display='table-row';
        $('game-ratings-hr').style.display='table-row';
    } else if ($('second-category') && $('second-category').options[$('second-category').selectedIndex].text == "Games") {
        $('game-ratings').style.display='table-row';
        $('game-ratings-hr').style.display='table-row';
    } else if ($('primary-category') && $('primary-category').options[$('primary-category').selectedIndex].text == "Games") {
        $('game-ratings').style.display='none';
        $('game-ratings-hr').style.display='none';
    } else if ($('second-category') && $('second-category').options[$('second-category').selectedIndex].text != "Games") {
        $('game-ratings').style.display='none';
        $('game-ratings-hr').style.display='none';
    }
} );

Event.observe( window, 'change', function () {

    if ($('primary-category') && $('primary-category').options[$('primary-category').selectedIndex].text == "Games") {
        $('game-ratings').style.display='table-row';
        $('game-ratings-hr').style.display='table-row';
    } else if ($('second-category') && $('second-category').options[$('second-category').selectedIndex].text == "Games") {
        $('game-ratings').style.display='table-row';
        $('game-ratings-hr').style.display='table-row';
    } else if ($('primary-category') && $('primary-category').options[$('primary-category').selectedIndex].text != "Games") {
        $('game-ratings').style.display='none';
        $('game-ratings-hr').style.display='none';
    } else if ($('second-category') && $('second-category').options[$('second-category').selectedIndex].text != "Games") {
        $('game-ratings').style.display='none';
        $('game-ratings-hr').style.display='none';
    }
} );

Event.observe( window, 'load', function () {

    if ($('primary-category') && $('primary-category').options[$('primary-category').selectedIndex].text == "Games") {
        $('first-game-1').style.display='table-row';
        $('first-game-2').style.display='table-row';
    } else if ($('primary-category') && $('primary-category').options[$('primary-category').selectedIndex].text == "Games") {
        $('first-game-1').style.display='none';
        $('first-game-2').style.display='none';
    };

    if ($('second-category') && $('second-category').options[$('second-category').selectedIndex].text == "Games") {
        $('second-game-1').style.display='table-row';
        $('second-game-2').style.display='table-row';
    } else if ($('second-category') && $('second-category').options[$('second-category').selectedIndex].text != "Games") {
        $('second-game-1').style.display='none';
        $('second-game-2').style.display='none';
    }
} );

//Games Category Functions

function PrimeGameSelect () {

    if ($('primary-category').options[$('primary-category').selectedIndex].text == "Games") {
       $('first-game-1').style.display='table-row';
       $('first-game-2').style.display='table-row';
    } else {
       $('first-game-1').style.display='none';
       $('first-game-2').style.display='none';
    }
};

function SecondGameSelect () {

    if ($('second-category').options[$('second-category').selectedIndex].text == "Games") {
       $('second-game-1').style.display='table-row';
       $('second-game-2').style.display='table-row';
    } else {
       $('second-game-1').style.display='none';
       $('second-game-2').style.display='none';
    }
};


//VOD Type Functions

function VodCheck () {
    if ($('vod-type').value=="0") {
        if (Prototype.Browser.IE)
            $('vod-release-date').style.display='block';
        else
            $('vod-release-date').style.display='table-row';
    } else {
        $('vod-release-date').style.display='none';
    }
};

Event.observe( window, 'load', function () {
    if ($('vod-type') && $('vod-type').value == "0") {
        $('vod-release-date').style.display='table-row';
    } else if ($('vod-type') && $('vod-type').value != "0") {
        $('vod-release-date').style.display='none';
    }
} );

//Track Level Advisory
function updateAllTracks (paValue) {
    if (confirm("Do you want to apply this change to all tracks on this playlist?\n\nClick OK to change all tracks, or Cancel to change only the track that you requested.")) {
     var i = 1;
        while ($('track-advisory' + i)) {
         var popUpId = "track-advisory" + i;
         $(popUpId).options[paValue].selected = true;
            i++;
     }
 }
}

//Confirm 'Remove From Sale' selection
function removeFromSale() {
    var remove = confirm(
            "You are removing your application from sale. Your application will be removed from sale in all countries. " +
            "To put it back on sale at any time, click Edit Information, go to the Rights and Pricing tab, and select the " +
            "countries in which you would like your application to be available. Click <OK> to continue or <Cancel> to " +
            "keep the application for sale.");
    if (remove) {
        return true;
    } else {
        return false;
    }
}

//Confirm 'Reject Binary' selection
function rejectBinary() {
    var remove = confirm(
            "Are you sure you want to reject this binary?\n\nClick OK to remove this binary from the system. It will not be reviewed or made available on the App Store.");
    if (remove) {
        return true;
    } else {
        return false;
    }
}

//Confirm continue action from Territories
function confirmTerritorySave(mode) {
    if (mode==1) {
        if (!readCookie('TerritoryAddPrompt')) {
            var save = confirm("Make sure you have saved each territory, then click OK to continue.");
            if (save) {
                createCookie('TerritoryAddPrompt','1',365);
                return true;
            } else {
                return false;
            }
        }
    } else {
        if (!readCookie('TerritoryEditPrompt')) {
            var save = confirm("Make sure you have saved each territory, then click OK to continue.");
            if (save) {
                createCookie('TerritoryEditPrompt','1',365);
                return true;
            } else {
                return false;
            }
        }
    }
}

//Switch available promo code view
function promoCodeView(index) {
    var codeArray = $$('div.codeString');
    for(i=0;i<codeArray.length;i++) {
        codeArray[i].style.display = "none";
    }
    var divId = "codes_"+index;
    $(divId).style.display = "block";
}

//Specify unique classes for even and odd table rows so we can change the backgrounds and hover states for readability
var AlternatingRowColorTable = function(element, options) {
  options = Object.extend({ even: 'even', odd: 'odd', hover: 'hover' }, options || {});
  $(element).select('tbody tr').each(function(row, index) {
    row.addClassName(index % 2 == 0 ? options.even : options.odd);
    row.observe('mouseover', function() { row.addClassName(options.hover) });
    row.observe('mouseout', function() { row.removeClassName(options.hover) });
  });
};


