var selMedia = new Array();
var mediaList = "";

womAdd('makeUniform(".media_name", ".media_add", ".media_image", ".media_descr", ".media_expires", ".searchResultFloat");');
womAdd('hideQtys();');
womAdd("updateStateField('');");

function verifyForm()
{
    // Clear old error messages
    $('message').innerHTML = "";
    
    var requiredFields = new Array(
        document.getElementById( "name" ),
        document.getElementById( "email" ),
        document.getElementById( "phone" ),
        document.getElementById( "compname" ),
        document.getElementById( "address1" ),
        document.getElementById( "city" ),
        document.getElementById( "zip" )
    );

    var results = verifyMedia();

    $( "state_text" ).style.backgroundColor = "white";
    for( var i = 0; i < requiredFields.length; i++ )
    {
        requiredFields[i].parentNode.parentNode.cells[0].style.backgroundColor = "white";
        if( requiredFields[i].value == "" )
        {
            requiredFields[i].parentNode.parentNode.cells[0].style.backgroundColor = "red";
            results = false;
        }
    }

    results = verifyEmail() && results;
    
    // US Check
    
    if( $('country').value == "US" && $('state').value == "" )
    {
        $( "state_text" ).style.backgroundColor = "red";
        $( "state" ).focus();
        results = false;
    }

    // Other country check
    if( $('country').value != "US" && $('state_input').value == "" )
    {
        $( "state_text" ).style.backgroundColor = "red";
        $( "state_input" ).focus();
        results = false;
    }

    if (results) {
    	$('order_str').value = mediaList;
    	$('orderForm').submit();
    }
    else
    	alert("Please complete or correct the highlighted fields.");
}

function verifyMedia()
{
    // Check if no media selected
    if (selMedia.length == 0) {
        $('message').innerHTML = "Please select at least one media item.";
        return false;
    }
    
    // Make a string of IDs and QTYs this form:
    // ID:QTY,ID:QTY,...,ID:QTY
    var tmpArr = new Array();
    //alert(selMedia.length);
    for (var id=0, len=selMedia.length; id < len; id++) {
        if ((selMedia[id] != null) && selMedia[id]) {
        	// This will change based on whether it is an input (hidden) or select
        	if ($('QTY'+id).type == "hidden") {
        		var selQty = $('QTY'+id).value;
        	}
        	else {
        		var selQtyInd = $('QTY'+id).selectedIndex;
        		var selQty = $('QTY'+id).options[selQtyInd].value;
        	}
            tmpArr.push(id+':'+selQty);
        }
    }
    mediaList = tmpArr.join(',');
    
    return true;
}

function verifyEmail()
{
    results = true;
    email = document.getElementById( "email" ).value;

    // Check if there is anything in the email field
    if (!email) results = false;

    // Check for invalid characters 
    if( email.search( /[\x00-\x1F\x7F-\xFF]/ ) > -1 ) results = false; 

    // Check that there's one @ symbol, and that the lengths are right 
    if( email.search( /^[^@]{1,64}@[^@]{1,255}$/ ) == -1 ) results = false; 

	// If there have been no errors so far, parse the email addr
	if (results) {

        // Split it into sections to make life easier 
        email_array = email.split( '@' ); 

        // Check local part 
        local_array = email_array[0].split( '.' ); 
        for( i=0; i<local_array.length; i++ )
        {
            if ( local_array[i].search( /^(([A-Za-z0-9!#$%&\'*+\/=?^_`{|}~-]+)|("[^"]+"))$/ ) == -1 ) results = false; 
        }

        // Check domain part 
        if( email_array[1].search( /^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}$/ ) > -1 || email_array[1].search( /^\[(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}\]$/ ) > -1 ) 
        {
            results = results && true; // If an IP address 
        }
        else
        { // If not an IP address 
            domain_array = email_array[1].split( '.' ); 
            if( domain_array.length < 2 ) results = false; // Not enough parts to be a valid domain 

            for( i=0; i<domain_array.length; i++ ) 
            {
                if( domain_array[i].search( /^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]))$/ ) == -1 ) results = false; 
            }
        }
    }

    if( !results )
    {
        document.getElementById( "emailRow" ).cells[0].style.backgroundColor = "red";
    }

    return results;
} 

function checkRadio(name)
{
    result = false;

    radios = document.getElementsByName(name);

    for( var i = 0; i < radios.length; i++)
    {
        if( radios[i].checked ) result = true;
    }

    if( !result ) {
        radios[0].parentNode.style.backgroundColor = "red";
    }

    return result;
}

function toggleQty( id )
{
    if( document.getElementById( "ID"+id ).checked )
    {
        document.getElementById( "QTY"+id ).style.visibility = "visible";
    } else {
        document.getElementById( "QTY"+id ).style.visibility = "hidden";
    }
}

// Add or remove a flyer from an order
function toggleMedia(id)
{
    if (selMedia[id] != null) {
        // Remove
        selMedia[id] = null;
        $('media_box'+id).style.backgroundColor = "lightgrey";
        $('add_media_text'+id).innerHTML = "[ Add to Order ]";
        if ($('QTY'+id) != null) {
        	$('media_add'+id).style.border = "1px solid white";
        	$('QTY'+id).hide();
        }
    }
    else {
        // Add
        selMedia[id] = true;
        $('media_box'+id).style.backgroundColor = "red";
        $('add_media_text'+id).innerHTML = "&nbsp;&nbsp;[ Remove from Order ]";
        if ($('QTY'+id) != null) {
        	//$('media_add'+id).style.border = "1px dotted royalblue";
        	$('QTY'+id).show();
        }
    }
}

function hideQtys() 
{
    $$('.media_qty').each( function(elm) { elm.hide(); } );
}

function updateStateField(prefix) {
	if ($(prefix+'country') == null || $(prefix+'country') == null) return;
	
    var i = $(prefix+'country').selectedIndex;
    var country = $(prefix+'country').options[i].value;
  
        if (country == 'US') {
        $(prefix+'state_text').innerHTML = "State:";
        $(prefix+'state_input').hide();
        $(prefix+'state').show();
    }
    else {
        $(prefix+'state_text').innerHTML = "State/Province:";
        $(prefix+'state').hide();
        $(prefix+'state_input').show();
    }
}