// JavaScript Document

function openWin( url, title, width, height ) {
    newWindow = window.open( url, title, "width="+width+",height="+height );
    newWindow.focus( );
}

// set the height of a div
function setDivHeight( divId, height ) {
    div = element( divId );
    div.style.height = height + 'px';
}

// expand a div down
function expand( divId, height, pixelMoveTime, dir ) {
    if( dir == 'down' ) {
        var pixel = 1;
        var time  = 0;
        while( pixel <= height ) {
            time  = time  + pixelMoveTime;
            pixel = pixel + 1;
            setTimeout( "setDivHeight( '" + divId + "', " + pixel + " )", time );
        }
	  } else {
        var pixel = height;
        var time  = 0;
        while( pixel > 0 ) {
            time  = time  + pixelMoveTime;
            pixel = pixel - 1;
            //alert( "setDivHeight( '" + divId + "', " + pixel + " )" );
            setTimeout( "setDivHeight( '" + divId + "', " + pixel + " )", time );
        }
    }
}

function pad0( divId ) {  // Defined to be used in the next 'show or hide menu' code
	div = element( divId );
	div.style.padding = 0;
}

// show or hide menu
function dropDown( fldId, height, pixelMoveTime ) {
    var container = element( fldId );
    var arr = element( fldId + 'Arr' ); // div containg arrow
    var img = arr.getAttribute( 'src' );
    var div = element( fldId + 'Data' );
    if( parseInt( div.style.height ) > 0 ) {
        arr.setAttribute( 'src', img.replace( /up/, 'down' ) );
        setTimeout( "pad0( '" + fldId + 'Data' + "' )", pixelMoveTime*height );
        expand( fldId + 'Data', height, pixelMoveTime, 'up' );
    } else {
        div.style.padding = '8px 8px 8px 12px';
        arr.setAttribute( 'src', img.replace( /down/, 'up' ) );
        expand( fldId + 'Data', height, pixelMoveTime, 'down' );
    }
    return;
}

function slideShow( total, current, imagesArr, imgTagId, prevSpanId, nextSpanId ) {
	// total      = Number of total images
	// current    = The image to show for now
	// imagesArr  = Images array
	// imgTagId   = The image placeholder ID where the image is updated
	// prevSpanId = The span tag ID which contains the link to the previous image
	// nextSpanId = The span tag ID which contains the link to the next image
	total = parseInt( total );
	current = parseInt( current );
	img      = element( imgTagId );
	prevSpan = element( prevSpanId );
	nextSpan = element( nextSpanId );
	if( total > 1 ) {
		if( current == 1 ) {
			prevSpan.innerHTML = '';
			nextSpan.innerHTML = "<a href=\"#\" onclick=\"slideShow( '" + total + "','" + 2 +"', imagesArr,'" + imgTagId + "','" + prevSpanId + "','" + nextSpanId + "' ); return false;\">Next</a>";
		} else if( current == total ) {
			prevSpan.innerHTML = "<a href=\"#\" onclick=\"slideShow( '" + total + "','" + (total-1) +"', imagesArr,'" + imgTagId + "','" + prevSpanId + "','" + nextSpanId + "' ); return false;\">Previous</a>";
			nextSpan.innerHTML = '';
		} else {
			prevSpan.innerHTML = "<a href=\"#\" onclick=\"slideShow( '" + total + "','" + (current-1) +"', imagesArr,'" + imgTagId + "','" + prevSpanId + "','" + nextSpanId + "' ); return false;\">Previous</a>";
			nextSpan.innerHTML = "<a href=\"#\" onclick=\"slideShow( '" + total + "','" + (current+1) +"', imagesArr,'" + imgTagId + "','" + prevSpanId + "','" + nextSpanId + "' ); return false;\">Next</a>";
		}
	} else {
		prevSpan.innerHTML = '';
		nextSpan.innerHTML = '';
	}
    img.src = imagesArr[ current - 1 ];
}


// SlideShow designed to show only a maximum of 10 images
function newSlideShow( total, imagesArr, imgTagId ) {
	var imgTag = element( imgTagId );
	// set all six thumbnails visibility to be visible
	for( var i=0; i<total; i++ ) {
		var img = element( imgTagId + 'T' + (i+1) );
		img.src = imagesArr[i];
		img.style.visibility = 'visible';
	}
	// hide the remaining images
	for( i; i<10; i++ ) {
		var img = element( imgTagId + 'T' + (i+1) );
		img.style.visibility = 'hidden';
	}
}

function MM_validateForm( ) { //v4.0
    // Argument interpretation:
    /* Argument 1: Field-ID
       Argument 2: Friendly-Name
       Argument 3: Requirement-Condition
    */
    if ( document.getElementById ) {
        var i, p, nm, test, num, min, max, args = MM_validateForm.arguments;
        for ( i = 0; i < ( args.length-2 ); i += 3 ) {
            test = args[i+2]; //required condition i.e. to be tested against
            // Values: 
            /* R                   = > Required,     Can be anything
               NisPh               = > Not Required, Should be a Phone Number
               RisPh               = > Required,     Should be a Phone Number
               NisNum              = > Not Required, Should be a Number
               RisNum              = > Required,     Should be a Number
               NisEmail            = > Not Required, Should be an Email Address
               RisEmail            = > Required,     Should be an Email Address
               NinRange[min]:[max] = > Not Required, Should be a Number in the Range [min] to [max]
               RinRange[min]:[max] = > Required,     Should be a Number in the Range [min] to [max]
            */
            val = element( args[i] ); //field
            if ( val ) { //if element exists
                nm = args[i+1]; //friendly field name
                if ( ( val = val.value ) != "" ) { //if value of field is not empty
                    if ( test.indexOf( 'isEmail' ) != -1 ) { //if test condition includes Email requirement
                        p = val.indexOf( '@' ); //check whether '@' symbol is in the string or not
                        if ( p < 1 || p == ( val.length-1 ) ) { //if '@' is not in the string or if it is at end of string
                            alert( nm + ' must be an e-mail address.\n' );
                            document.MM_returnValue = false;
                            element( args[i] ).style.borderColor = '#CC0000';
                            element( args[i] ).focus( );
                            return false;
                        }
                    //endif condition includes Email reuirement
					} else if ( test.indexOf( 'isPh' ) != -1 ) { //if test condition includes Phone requirement
                        p = val;
                        p = p.replace( /[+]/, '00' ); //replace plus symbol from start
                        while( p.search( /\s+/ ) != -1 ) {
                            p = p.replace( /\s+/, '' ); //remove all whitespaces
						}
                        while( p.search( /[\-\(\)]/ ) != -1 ) {
                            p = p.replace( /[\-\(\)]/, '' ); //remove all dashes and parenthesis
                        }
                        if ( p.search( /\D+/ ) != -1 ) { //if still there are some non-numeric characters left
                            alert( nm + ' must be a phone number.\n+ - ( ) and [space] characters can be used within number.' );
                            document.MM_returnValue = false;
                            element( args[i] ).style.borderColor = '#CC0000';
                            element( args[i] ).focus( );
                            return false;
                        }
                    //endif condition includes Phone reuirement
                    } else if ( test != 'R' ) { //else there must be some other requirement i.e. Number required
                        num = parseFloat( val );
                        if ( isNaN( val ) ) { //if the value is not a number
                            alert( nm + ' must be a number.\n' );
                            document.MM_returnValue = false;
                            element( args[i] ).style.borderColor = '#CC0000';
                            element( args[i] ).focus( );
                            return false;
                        }
                        if ( test.indexOf( 'inRange' ) != -1 ) { //if further range test condition is included
                            p = test.indexOf( ':' );
                            min = test.substring( 8, p );  //get lower limit
                            max = test.substring( p + 1 ); //get upper limit
                            if ( num < min || max < num) {//if limits are not followed
                                alert( nm + ' must be a number between ' + min + ' and ' + max + '.\n' );
                                document.MM_returnValue = false;
                                element( args[i] ).style.borderColor = '#CC0000';
                                element( args[i] ).focus( );
                                return false;
                            }//endif limits were not followed
                        }//endif further range test condition was included
                    }//endelse Number required
                //endif value of field was not empty
                } else if ( test.charAt( 0 ) == 'R' ) { //else if value of field is empty & if it is required
                    alert( nm + ' is required.\n' );
                    document.MM_returnValue = false;
                    element( args[i] ).style.borderColor = '#CC0000';
                    element( args[i] ).focus( );
                    return false;
                }//endelse if value of field was empty & if it was required
            } //endif element exists
        }//endfor
        document.MM_returnValue = true;
    }//endif Main
}

// Add contact field
function addRow( tbl, count )
{
  if( count < 10 ) {
    count = count + 1;
    code1 = '<input name="features[]" type="text" id="features[]" size="45" />';
    var table = element( tbl );
    var tr = document.createElement( 'tr' );
    table.tBodies[0].appendChild( tr );
    var td1 = document.createElement( 'td' );
    td1.innerHTML = code1;
    tr.appendChild( td1 );
  } else {
    alert( 'You can not add more than 10 fields!' );
  }
  return count;
}

// Add Picture field
function addPic( tbl, pcount )
{
  if( pcount < 20 ) {
    pcount = pcount + 1;
    code1 = '<input name="file[]" type="file" id="file[]"/>';
    var table = element( tbl );
    var tr = document.createElement( 'tr' );
    table.tBodies[0].appendChild( tr );
    var td1 = document.createElement( 'td' );
    td1.innerHTML = code1;
    tr.appendChild( td1 );
  } else {
    alert( 'You can not add more than 10 fields!' );
  }
  return pcount;
}

function addPicEvent( tbl, pcount )
{

  if( pcount < 1 ) {
    pcount = pcount + 1;
    code1 = '<input name="file[]" type="file" id="file[]"/>';
    var table = element( tbl );
    var tr = document.createElement( 'tr' );
    table.tBodies[0].appendChild( tr );
    var td1 = document.createElement( 'td' );
    td1.innerHTML = code1;
    tr.appendChild( td1 );
  } else {
    alert( 'You can not add more than 2 Pictures!' );
  }
  return pcount;
}




// Add Colour field
function addColour( tbl, ccount )
{
  if( ccount < 20 ) {
    ccount = ccount + 1;
    code1 = '<input name="colour[]" type="text" id="colour[]"/>';
    var table = element( tbl );
    var tr = document.createElement( 'tr' );
    table.tBodies[0].appendChild( tr );
    var td1 = document.createElement( 'td' );
    td1.innerHTML = code1;
    tr.appendChild( td1 );
  } else {
    alert( 'You can not add more than 10 fields!' );
  }
  return ccount;
}

function editRow( tbl,count )
{
  code1 = '<input name="features[]" type="text" id="features[]" size="45" />';
  var table = element( tbl );
  var tr = document.createElement( 'tr' );
  table.tBodies[0].appendChild( tr );
  var td1 = document.createElement( 'td' );
  td1.innerHTML = code1;
  tr.appendChild( td1 );
}


function toNumber( val ) {
  var num = '';
  val = val.toString();
  for( var i=0; i<val.length; i++ ) {
    if( !isNaN( parseInt( val.charAt(i) ) ) ) {
      num = num + parseInt( val.charAt(i) ).toString();
    } 
  }
  return num;  
}

function element( id ) {
  return document.getElementById( id );
}

function updateFld( id, val ) {
  element( id ).value = val;
}


function fldValue( id ) {
  return element( id ).value;
}


function showElement( id ) {
  element( id ).style.visibility = 'visible';
}


function hideElement( id ) {
  element( id ).style.visibility = 'hidden';
}


function price( val ) {
  var num = '';
  num = toNumber( val );
  var strnum = '';
  for( i=num.length-1, j=0; i>-1; i--, j++ ) {
    if( j!=0 && (j%3)==0 && j<num.length ) {
	  strnum = ',' + strnum;
	}
	strnum = num.charAt(i) + strnum;
  }
  return strnum;
}

function extensionChk( ext, fld ) {
  fld = fldValue( fld );
  if( fld.indexOf( ext ) && fld.length <= fld.indexOf( ext )+4  ) {
    return true;
  }
  alert( 'Warning: Only .' + ext + ' files are allowed.' );
  return false;
}


function callAjax( frmName ) {
  disableForm( frmName );
  var str = '?';
  str += 'nameT='  + fldValue( 'fname' ) + '&fname='  + fldValue( 'fname' ) +
         '&sname=' + fldValue( 'sname' ) + '&postcd=' + fldValue( 'postcode' ) +
         '&email=' + fldValue( 'email' ) + '&ph_hm='  + fldValue( 'ph_home' ) +
         '&ph_mb=' + fldValue( 'ph_mobile' );
												
  var fnDone = function( oXML ) {
    var returned = oXML.responseText;
    if( returned != '' ) {
      element( 'result' ).innerHTML = returned;
      window.scrollBy( 0, -300 );
	  window.location = '#result';
    } else {
      element( 'result' ).innerHTML = '';
    }
    hideElement( 'checking' );
    enableForm( frmName );
  }

  var AJAX = new XHConn( );
  AJAX.connect( 'chkmatch.php', 'POST', str, fnDone );
}


function getRegion( country ) {
  var str = '?';
  str += 'cT=' + country + '&c=' + country;											
  var fnDone = function( oXML ) {
    var returned = oXML.responseText;
	element( 'regionSel' ).innerHTML = returned;
    element( 'region' ).focus( );
  }
  var AJAX = new XHConn( );
  AJAX.connect( 'getregion.php', 'POST', str, fnDone );
}

/*function getCategory( pCategory ) {
  var str = '?';
  str += 'cT=' + pCategory + '&c=' + pCategory;												
  var fnDone = function( oXML ) {
    var returned = oXML.responseText;
    element( 'regionSel' ).innerHTML = returned;
    element( 'region' ).focus( );
  }
  
    var AJAX = new XHConn( );
  AJAX.connect( 'getCategory.php', 'POST', str, fnDone );
}*/

function getCateg( categ ) {
  var str = '?';
  str += 'cT=' + categ + '&c=' + categ;											
  var fnDone = function( oXML ) {
    var returned = oXML.responseText;
	document.getElementById("catSel1").style.visibility="hidden";
    element( 'catSel' ).innerHTML = returned;
    element( 'category' ).focus( );
  }
  var AJAX = new XHConn( );
  AJAX.connect( 'getcategory.php', 'POST', str, fnDone );
}

function getCateg1( categ ) {
 
  var str = '?';
  str += 'cT=' + categ + '&c=' + categ;											
  var fnDone = function( oXML ) {
  var returned = oXML.responseText;
  	document.getElementById("catSel1").style.visibility="visible";
  element( 'catSel1' ).innerHTML = returned;
  element( 'category1' ).focus( );
  }
  var AJAX = new XHConn( );
  AJAX.connect( 'getcategory1.php', 'POST', str, fnDone );
}

function getTemplate( template ) {
  var str = '?';
  str += 'cT=' + template + '&c=' + template;
												
  var fnDone = function( oXML ) {
    var returned = oXML.responseText;
    element( 'regionSel' ).innerHTML = returned;
    
  }

  var AJAX = new XHConn( );
  AJAX.connect( 'gettemplate.php', 'POST', str, fnDone );
}

function getEvent( categ ) {
  
  
  var str = '?';
  str += 'cT=' + categ + '&id=' + categ;											
  var fnDone = function( oXML ) {
    var returned = oXML.responseText;
    element( 'showEvent' ).innerHTML = returned;
    
  }
  var AJAX = new XHConn( );
  AJAX.connect( 'getevent.php', 'POST', str, fnDone );
}



// Disable form
var elStatus = Array( );
function disableForm( frmName ) {
  var i = 0;
  frm = document.getElementById( frmName );
  while( frm.elements[i] ) {
    elStatus[i] = false;
    if( frm.elements[i].disabled == true ) {
      elStatus[i] = true;
    }
    frm.elements[i++].disabled = true;
  }
}

// Enable Form
function enableForm( frmName ) {
  var i = 0;
  frm = document.getElementById( frmName );
  while( frm.elements[i] ) {
    frm.elements[i].disabled = elStatus[i++];
  }
}
