/* 
 * PHP File Uploader with progress bar Version 1.20
 * Copyright (C) Raditha Dissanyake 2003
 * http://www.raditha.com

 * Licence:
 * The contents of this file are subject to the Mozilla Public
 * License Version 1.1 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 * 
 * Software distributed under the License is distributed on an "AS
 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * rights and limitations under the License.
 * 
 * The Initial Developer of the Original Code is Raditha Dissanayake.
 * Portions created by Raditha are Copyright (C) 2003
 * Raditha Dissanayake. All Rights Reserved.
 * 
 */
 

//var postLocation="/pgbar.php";
var postLocation="/cgi-bin/progress.cgi";

/* 
 * add any extension that you do no want to upload to the list 
 * below they should be placed with in the /^ and / characters
 * separate each extension by a pipe symbol |
 */
 
var re = /^(\.php)|(\.sh)|(\.exe)/;  // disallow shell scripts and php


/**
 * dofilter = true; to enable filtering
 */
var dofilter = true;

var photo_i = 0;

/* 
 * add a new file upload field to the form
 */
function add_image_upload()
{
    photo_i++;
    $('#upload_photos').append('<div style="margin:10px 14px;"><input id="file_'+photo_i+'" type="file" name="file['+photo_i+']">&nbsp;<button onclick="$(this).parent().remove()">remove</button></div>');
}


/**
 * this method will match each of the filenames with a
 * given list of banned extension. If any one of the
 * extensions match, an alert will be popped up and the
 * upload will not continue;
 */
 
function check_types()
{
	if ( dofilter == false )
	{
		return true;
	}
	with ( document.forms[0] )
	{
		/*
		 * with who uses with?
		 * i do, i am an ancient. ok?
		 */
		
		for ( i=0 ; i < elements.length ; i++ )
		{
			if ( elements[i].value.match(re) )
			{
				alert('Sorry ' + elements[i].value + ' is not allowed');
				return false;
			}
		}
	}
	return true;
}

function popUP( mypage )
{
    $('#light').css({display:'block'});
   	$('#light').empty();
    $('#fade').css({display:'block'});
    //$('#light').append('<iframe id="uploader_prog" src="http://google.com.au"></iframe>');
    $('#light').append('<iframe name="uploader_prog" id="uploader_prog" border="0" style="border: none;" src="'+mypage+'"></iframe>');

/*	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable'
	win = window.open(mypage, myname, winprops)
	if (parseInt(navigator.appVersion) >= 4) {
		win.window.focus();
	}
*/
}

function validateInput(id)
{
    if ( !$(id).val() )
    {
        $(id).css({border:'2px solid red'});
        $(id).prev("label").css({color:'red','font-weight':'bold'});
        return false;
    }
    else
    {
        $(id).css({border:'none'});
        $(id).prev("label").css({color:'#5f5758','font-weight':'normal'});
        return true;
    }
}


function check_fields()
{
    var good = true;
    var err = [];
    //$.get('captcha_check',{captcha: captcha_string},function(data){pre_cap_check=data;});
    
    $('#light').empty().css({display:'block'});
    $('#fade').css({display:'block'});
    // $('#light').append('Checking form fields...<br><br>'+"\nChecking categories...");
    
    
    // Check Ad_Type field
    if ( !$(":input[name='Ad_Type'][@checked]").val() )
    {
        $('#ad_type_box').css({border:'2px solid red'});
        $('#ad_type_box').prev('h5').css({color:'red'});
        err.push("Type of Advertisement");
        good = false;
    }
    else
    {
        $('#ad_type_box').css({border:'none'});
        $('#ad_type_box').prev('h5').css({color:'#00ace2'});
    }
    
    // Check Colour_Options field
//    if ( !$(":input[name='Colour_Options'][@checked]").val() )
//    {
//        $('#colour_options_box').css({border:'2px solid red'});
//        $('#colour_options_box').prev('h5').css({color:'red'});
//        err.push("Colour Printing Options");
//        good = false;
//    }
//    else
//    {
//        $('#colour_options_box').css({border:'none'});
//        $('#colour_options_box').prev('h5').css({color:'#00ace2'});
//    }
    
    // Check Ad_Instruction field
    if ( !$(":input[name='Ad_Instruction']").val() )
    {
        $(":input[name='Ad_Instruction']").css({border:'2px solid red',backgroundColor:'#fffafa'});
        $(":input[name='Ad_Instruction']").parent().prev("h5").css({color:"red"});
        err.push("Ad Text");
        good = false;
    }
    else
    {
        $(":input[name='Ad_Instruction']").css({border:'1px solid black',backgroundColor:'#ffffff'});
        $(":input[name='Ad_Instruction']").parent().prev("h5").css({color:"#00ace2"});
    }
    
    
    // Check Category field
    if ( !$('#Category').val() )
    {
        $('#Category').parent().prev("h5").css({color:'red'});
        $('#Category').css({border:'2px solid red',backgroundColor:'#fffafa'});
        err.push("Web Search Category");
        good = false;
    }
    else
    {
        $('#Category').parent().prev("h5").css({color:'#00ace2'});
        $('#Category').css({border:'1px solid black',backgroundColor:'#ffffff'});
    }

    
    // Check Duration field
    if ( !$(":input[name='Duration'][@checked]").val() )
    {
        $("#duration_box").css({border:'2px solid red',backgroundColor:'#fffafa'});
        $("#duration_box").prev("h5").css({color:'red'});
        err.push("Number of Issues");
        good = false;
    }
    else
    {
        $("#duration_box").css({border:'none',backgroundColor:'transparent'});
        $("#duration_box").prev("h5").css({color:'#00ace2'});
    }
    
    
    // Check Contact_Name field
    if ( !validateInput("#Contact_Name") )
    {
        err.push("Contact Name");
        good = false;
    }
   
    
    // Check Address field
    if ( !validateInput("#Address") )
    {
        err.push("Postal Address");
        good = false;
    }
    

    // Check City field
    if ( !validateInput("#City") )
    {
        err.push("City/Suburb");
        good = false;
    }
    
    
    // Check Post_Code field
    if ( !validateInput("#Post_Code") )
    {
        err.push("Post/Zip Code");
        good = false;
    }
    
    
    // Check State field
    if ( !validateInput("#State") )
    {
        err.push("State");
        good = false;
    }
    
    
    // Check Country field
    if ( !validateInput("#Country") )
    {
        err.push("Country");
        good = false;
    }
    
    
    // Check Phone_BH field
    if ( !validateInput("#Phone_BH") )
    {
        err.push("BH Phone");
        good = false;
    }
    
    
    // Check E-mail field
    var emlreg = /^([A-Za-z0-9_+\.\-])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if ( !validateInput("#E-mail") )
    {
        err.push("E-mail");
        good = false;
    }
    else if ( emlreg.test( $('#E-mail').val() ) == false )
    {
        $('#E-mail').css({border:'2px solid red'});
        $('#E-mail').prev("label").css({color:'red','font-weight':'bold'});
        err.push("valid E-mail address");
        good = false;
    }
    else
    {
        $('#E-mail').css({border:'none'});
        $('#E-mail').prev("label").css({color:'#5f5758','font-weight':'normal'});
    }

    
    
    // Check for invalid Capcha before server pre validation to save network lag
    var captcha_string = $('#captcha').val();
    if ( (captcha_string.length < 5) || (captcha_string.length > 5) )
    {
        $('#captcha').css({border:'2px solid red'});
        $('#captcha').prev("label").css({color:'red','font-weight':'bold'});
        err.push("Security Code");
        good = false;
    }
    else
    {
        $('#captcha').css({border:'none'});
        $('#captcha').prev("label").css({color:'#5f5758','font-weight':'normal'});
    }
    

    
    if ( !good )
    {
        var plural = (err.length > 1)?"s are":" is";
        if ( err.length )        var err = "<p>The following field"+plural+" required<br>"+err.join(", ")+"</p>";
        $('#light').append(err+'<p>Please enter the required details in the highlighted fields</p><p><a href="javascript:void(0);" onclick="$(\'#light\').fadeOut(\'slow\');$(\'#fade\').fadeOut(\'slow\');"><strong>Continue</strong></a></p>'+"\n");
        return false;
    }
    
    
    $('#light').append('<p>Checking security code..</p>');
    // show progress indicator
    
    var pre_cap_check = '0';
    
    if ( good && captcha_string.length == 5 )
    {
        pre_cap_check = jQuery.ajax({
             url:    'captcha_check' 
                      + '?captcha=' 
                      + captcha_string,
             async:   false
        }).responseText;   
    }
    
    if ( pre_cap_check == '0' )
    {
        $('#captcha').css({border:'2px solid red'});
        $('#light').append('<p>The security code was incorrect. Please try again.</p><p>(The security code is not case-sensitive).</p><p><a href="javascript:void(0);" onclick="$(\'#light\').fadeOut(\'slow\');$(\'#fade\').fadeOut(\'slow\');"><strong>Continue</strong></a></p>'+"\n");
        good = false;
    }
    else
    {
        $('#light > p').append(' good.<br>'+"\n");
        $('#captcha').css({border:'none'});
    }


    if ( good )
    {
        return true;
    }
    else
    {
        return false;
    }
}


function postIt()
{

    $('#advertisement_sub_form').attr('action','/cgi-bin/upload.cgi?sid='+$('#sessionid').val());
    $('#advertisement_sub_form').attr('target','hid_sub');

	if ( check_types() == false )
	{
		return false;
	}
	if ( check_fields() == false )
	{
    		isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
    		if(isIE6) 
    		{
			alert("Please fix the highlighted errors on the form");
		    $('#light').empty().css({display:'none'});
		    $('#fade').css({display:'none'});
	
   		 }
		return false;
	}
	
    $('#light').empty();

	baseUrl = postLocation;
	sid = document.forms[0].sessionid.value;
	iTotal = escape("-1");
	baseUrl += "?iTotal=" + iTotal;
	baseUrl += "&iRead=0";
	baseUrl += "&iStatus=1";
	baseUrl += "&sessionid=" + sid;
	baseUrl += "&dtstart=" + new Date()/1000;

	popUP(baseUrl);
    //	$('#advertisement_sub_form').submit();
    return true;
}

function resetForm(id) {
	$('#'+id).each(function(){
	        this.reset();
	});
}
