// Control multiple onload functions
function addOnload(fnc) {
	if(typeof fnc == "function") {
		if ( typeof window.addEventListener != "undefined") {
			window.addEventListener( "load", fnc, false );
		} else if ( typeof window.attachEvent != "undefined" ) {
				window.attachEvent( "onload", fnc );
		} else {
			if ( window.onload != null ) {
				var oldOnload = window.onload;
				window.onload = function () {
					oldOnload();
					window[fnc]();
				};
			} else {
				window.onload = fnc;
			}
		}
	}
}

// Get elements with a particular class name.
document.getElementsByClassName = function(cl) {
	var retnode = [];
	var myclass = new RegExp("\\b"+cl+"\\b");
	var elem = this.getElementsByTagName("*");
	for (var i = 0; i < elem.length; i++) {
		var classes = elem[i].className;
		if (myclass.test(classes)) {
			retnode.push(elem[i]);
		}
	}
	return retnode;
};

var ticketcount = 1;
var datecount = 1;
var imagecount = 1;
var iKeywordCount = 2;
function add_option(div) {
	var newdiv = document.createElement('div');
	switch (div) {
		case 'dates':
			datecount++;
            // Welcome to a nice and complicated block of javascript....
            // initiate some elements we're going to need to play with.
            
            var newrow = document.createElement('tr');
            var newcellblank = document.createElement('td');
            var newcellstart = document.createElement('td');
            var newcellend = document.createElement('td');
            newcellblank.style.textAlign = 'left';
            
            // Apply some styles where necessary.
            newcellblank.className = 'listing_field_title';

            newcellblank.innerHTML = '&nbsp;';            
            // Add some content to the content cells.
            newcellstart.innerHTML ="\n<input id='from_" + datecount + "' name='from_" + datecount + "' class='field short' onclick='displayDatePicker(\"from_" + datecount + "\");' value='' autocomplete='off' />";
            newcellend.innerHTML ="\n<input id='to_" + datecount + "' name='to_" + datecount + "' class='field short' onclick='displayDatePicker(\"to_" + datecount + "\");' value='' autocomplete='off' />";

            // Add the rows first, then append the cells as children to the rows.
            document.getElementById('dates_info').appendChild(newrow);
            newrow.appendChild(newcellblank);
            newrow.appendChild(newcellstart);
            newrow.appendChild(newcellend);
			break;
		case 'tickets':
			ticketcount++;
             // Welcome to a nice and complicated block of javascript....
            // initiate some elements we're going to need to play with.
            
            var newrow = document.createElement('tr');
            var newcellblank = document.createElement('td');
            var newcellstart = document.createElement('td');
            var newcellend = document.createElement('td');
            newcellblank.style.textAlign = 'left';
            
            // Apply some styles where necessary.
            newcellblank.className = 'listing_field_title';

            newcellblank.innerHTML = '&nbsp;';            
            // Add some content to the content cells.
            newcellstart.innerHTML ="\n<input id='type_" + ticketcount + "' name='type_" + ticketcount + "' class='field short' value='' />";
            newcellend.innerHTML ="\n<input id='amount_" + ticketcount + "' name='amount_" + ticketcount + "' class='field short' value='' />";

            // Add the rows first, then append the cells as children to the rows.
            document.getElementById('tickets_info').appendChild(newrow);
            newrow.appendChild(newcellblank);
            newrow.appendChild(newcellstart);
            newrow.appendChild(newcellend);           

			break;
		case 'images':
			imagecount++;
			//newdiv.innerHTML = "<br /><label for='image"+imagecount+"'>New Image "+imagecount+":</label>\n<input type='file' name='image"+imagecount+"'>\n"
			//	+"<label for='image"+imagecount+"alt'>Description:</label>\n<input type='text' name='image"+imagecount+"alt'>\n"
			//	+"<label for='image"+imagecount+"title'>Title:</label>\n<input type='text' name='image"+imagecount+"title'>\n";
            var newrow = document.createElement('tr');
            var newcellimage = document.createElement('td');
            var newcellalt = document.createElement('td');
            var newcelltitle = document.createElement('td');
            
                   strSomething = "<tr>"
                    +"<td><input type='file' name='image"+imagecount+"'></td>"
                    +"<td></td>"
                    +"<td><input type='text' name='image"+imagecount+"title'></td>"
                    "</tr>";

            newcellimage.innerHTML = "<input type='file' name='image"+imagecount+"'>";
            newcellalt.innerHTML = "<input type='text' name='image"+imagecount+"alt'>";
            newcelltitle.innerHTML = "<input type='text' name='image"+imagecount+"title'>";

			document.getElementById('image_table').appendChild(newrow);
            newrow.appendChild(newcellimage);
            newrow.appendChild(newcellalt);
            newrow.appendChild(newcelltitle);
			break;
        case 'keyword':
            if(iKeywordCount < 10) {
              
              newdiv.style.padding = '3px';
              iKeywordCount++;
              newdiv.innerHTML = iKeywordCount+".<input type='text' name='keyword"+iKeywordCount+"' value='' style='width: 225px;' />";
              document.getElementById('keywords_list').appendChild(newdiv);
            } 
            
            if(iKeywordCount == 10) {
              document.getElementById('keywordLink').style.display = 'none';
            }
            break;
	}
}

function print_r( array, return_val ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Michael White (http://getsprink.com)
    // +   improved by: Ben Bryan
    // +      input by: Brett Zamir
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: print_r(1, true);
    // *     returns 1: 1
    
    var output = "", pad_char = " ", pad_val = 4;
 
    var formatArray = function (obj, cur_depth, pad_val, pad_char) {
        if (cur_depth > 0) {
            cur_depth++;
        }
 
        var base_pad = repeat_char(pad_val*cur_depth, pad_char);
        var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
        var str = "";
 
        if (obj instanceof Array || obj instanceof Object) {
            str += "Array\n" + base_pad + "(\n";
            for (var key in obj) {
                if (obj[key] instanceof Array) {
                    str += thick_pad + "["+key+"] => "+formatArray(obj[key], cur_depth+1, pad_val, pad_char);
                } else {
                    str += thick_pad + "["+key+"] => " + obj[key] + "\n";
                }
            }
            str += base_pad + ")\n";
        } else if(obj == null || obj == undefined) {
            str = '';
        } else {
            str = obj.toString();
        }
 
        return str;
    };
 
    var repeat_char = function (len, pad_char) {
        var str = "";
        for(var i=0; i < len; i++) { 
            str += pad_char; 
        }
        return str;
    };
    output = formatArray(array, 0, pad_val, pad_char);
 
    if (return_val !== true) {
        document.write("<pre>" + output + "</pre>");
        return true;
    } else {
        return output;
    }
}

function alert_r() {
        var alerts = new Array();
        for (var i = 0; i < arguments.length; i++) {
                alerts.push(print_r(arguments[i],true).replace(/ /g,String.fromCharCode(160)));
        }
        alert(alerts.join('\n'));
}


/*
  Google search functions
    Added by Rob Terry, 9th Dec 2009.
*/


var globalSearch;
var searchFunction = function() {
  // Does the search for the element name return any results?
  eSearch = document.getElementsByName('search');
  // If our search returned some results, then...
  if(eSearch.length > 0) {
    // We should be able to work with the result field.
    if(eSearch.item(0).name == 'search') {
        // set the globalSearch variable.
        globalSearch = eSearch.item(0);
    }
  } else {
    // Otherwise we'll have to do it the old fashioned way!
    eInput = document.getElementsByTagName('input');

    // Loop the tagname results and search for the one with the search name.
    for(var i = 0; i < eInput.length; i++)
    {
      // Grab the item and set a variable to the object for the duration of the loop.
      var obj = eInput.item(i);
      
      // If the object we're currently viewing has the name set to search, then that's
      // the object we're looking for. It's the search input field.
      if(obj.name == 'search') {
        // Set the globalSearch variable to being the object we're looking at now, so we
        // can do some stuff with it later on!
        globalSearch = obj;
      }
    }
  }

  // Finally, we need to add a listener for the clicking of the clear button.
  eClearTD = document.getElementsByTagName('td');
  for(var i = 0; i < eClearTD.length; i++) {
    // Set the object to the search result.
    var obj = eClearTD.item(i);
    
    // If the objects class name is the same as the clear button class, then we are
    // looking at the right table cell.
    if(obj.className == 'gsc-clear-button')
    {
      // Attach the onclick event.
      AttachEvent(obj, 'click',searchClear);
    }
  }

  // Finally, we need to add a listener for the clicking of the clear button.
  eSearchButton = document.getElementsByTagName('input');
  for(var i = 0; i < eSearchButton.length; i++) {
    // Set the object to the search result.
    var obj = eSearchButton.item(i);
    
    // If the objects class name is the same as the clear button class, then we are
    // looking at the right table cell.
    if(obj.className == 'gsc-search-button' && obj.value == 'Search')
    {
      // Attach the onclick event.
      AttachEvent(obj, 'click',searchSubmit);
    }
  }
}

// AttachEvent()
// Params:
//  el          - Element we're attaching the event to.
//  event       - Type of event to attach.
//  myFunction  - Function name without parenthesis.
// Returns:
//  Attaches the required function to the object for the given event.
// Revisions:
//  Created by Rob Terry, 9th Dec 2009.
function AttachEvent(el, event, myFunction){
  if( el.addEventListener ) {
    el.addEventListener(event,myFunction,false);
  } else if( el.attachEvent ) {
    el.attachEvent('on'+event,myFunction);
  }
} 

// searchClear()
// Params:
//  None.
// Returns:
//  Set's the search div to dissapear.
// Revisions:
//  Created by Rob Terry, 9th Dec 2009.
function searchSubmit() {
  // Does the search field have any content?
  if(globalSearch.value == '') {
    // If so, then set the boolean to false, so the search div will dissapear.
    b = false;
  } else {
    // Otherwise, it needs to be displayed.
    b = true;
  } 
  searchDivDisplay(b);
}


// searchClear()
// Params:
//  None.
// Returns:
//  Set's the search div to dissapear.
// Revisions:
//  Created by Rob Terry, 9th Dec 2009.
function searchClear() {
  // Set the div to dissapear.
  searchDivDisplay(false);
}

// searchDivDisplay()
// Params:
//  bDisplay [BOOL] -   TRUE if the search div should be displayed.
//                      FALSE if otherwise.
// Returns:
//  Show's or Hides the search div, dependant on the boolean value passed.
// Revisions:
//  Created by Rob Terry, 9th Dec 2009.
function searchDivDisplay(bDisplay) {

  // Grab the search content div.
  searchContent = document.getElementById('searchDiv');
  
  // If display is set to TRUE
  if(bDisplay == true)
  {
    // Show the search results and hide the other columns.
    searchContent.style.display = 'block';
    document.getElementById('column_1').style.display = 'none';
    document.getElementById('column_2').style.display = 'none';
    document.getElementById('homeDiv').style.display = 'none';
  } else {
    // Otherwise, hide the search div and display the original content.
    searchContent.style.display = 'none';
    document.getElementById('column_1').style.display = 'block';
    document.getElementById('column_2').style.display = 'block';
    document.getElementById('homeDiv').style.display = 'block';
  }
}

/*
  add listings javascript
*/

function startSearch() {
  document.getElementById('searchingDiv').style.display = 'inline';
}