﻿$(document).ready(function () {
  $('.onoff :checkbox').iphoneStyle({ checkedLabel: 'YES', uncheckedLabel: 'NO' });
  $("#searchsuburbs").click(function () {
    var sValue = (($("#txtWidgetSuburb").val() != "") ? $("#txtWidgetSuburb").val() : $("#txtWidgetPostcode").val());
    winRef = window.open("suburbsearch.aspx?value=" + sValue, "suburbMatchWin", "left=40,top=40,width=240,height=185,toolbar=0,resizable=0,statusbar=0");
  });
  $("#btnCreateWidgetReport").click(function () {
    if ($("#txtWidgetSuburb").val() != "" && $("#txtWidgetPostcode").val() != "") {
      $("#widgetspinner").stop(true, true).fadeIn("fast").delay(15000, function () { $("#widgetspinner").fadeOut("fast"); });
    }
  });
  $("#btnCreateReport").click(function () {
    //    $("#feedback").stop(true, true).fadeIn("fast").pulse({
    //      backgroundColors: ['#ffffff', '#fff5bc'],
    //      speed: 600
    //    }).delay(1500, function () { $("#feedback").recover(); }).delay(30000, function () { $("#feedback").fadeOut("fast"); });
    var LoaderWrapper = $(document.createElement('div'));

    $(LoaderWrapper).attr("id", "loader-wrapper");
    $(LoaderWrapper).css({
      'height': $(".tab-container").height() + 50 + 'px',
      'width': $(".tab-container").width() + 2 + 'px',
      'position': 'absolute',
      'top': '-40px',
      'left': '-1px',
      'background': '#fff url(images/ajax-preloader.gif) no-repeat center center',
      'z-index': '1001',
      'filter': 'alpha(opacity=80)',
      'opacity': '0.8'
    });

    $(LoaderWrapper).html("<span id=\"loader-close-image\" style=\"display:block;cursor:pointer;position:absolute;top:10px;right:10px;height:16px;width:16px;font:bold 12pt Arial;\">X</span>");
    $(".tab-container").append(LoaderWrapper);

    setTimeout('$("#loader-wrapper").remove()', 30000);
  });
  $("#loader-close-image").live("click", function () {
    $("#loader-wrapper").remove();
  });
  jQuery.fn.delay = function (time, func) {
    return this.each(function () {
      setTimeout(func, time);
    });
  };
  $('.upload_button').each(function () {
    var ctrlID = $(this).attr("id");
    var strEACPROPKEY = $(this).attr("id").split('_').slice(-1);
    var strEACMLSNUM = Number(strEACPROPKEY) + 300000000;
    new AjaxUpload(this, {
      // Location of the server-side upload script
      action: 'imgUpload.aspx',
      // Additional data to send
      data: {
        eacpropkey: strEACPROPKEY
      },
      // Submit file after selection
      autoSubmit: true,
      // The type of data that you're expecting back from the server.
      // Html (text) and xml are detected automatically.
      // Only useful when you are using json data as a response.
      // Set to "json" in that case.
      responseType: false,
      // Fired after the file is selected
      // Useful when autoSubmit is disabled
      // You can return false to cancel upload
      // @param file basename of uploaded file
      // @param extension of that file
      onChange: function (file, extension) { },
      // Fired before the file is uploaded
      // You can return false to cancel upload
      // @param file basename of uploaded file
      // @param extension of that file
      onSubmit: function (file, ext) {
        if (!(ext && /^(jpg|jpeg)$/.test(ext))) {
          // extension is not allowed
          alert('Error: only jpg files are allowed.');
          // cancel upload
          return false;
        }
        else
          $("#" + ctrlID).html("<img src=\"images/spinner.gif\" alt=\"Uploading image\" />");
      },
      // Fired when file upload is completed
      // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
      // @param file basename of uploaded file
      // @param response server response
      onComplete: function (file, response) {
        var txt = new RegExp(name, "i");
        if (response.match(txt)) {
          $("#" + ctrlID).remove();
          $("#parent_" + strEACPROPKEY).html("<img src=\"images/tick.gif\" alt=\"This property has images.\" />");
          $("#wfphoto_" + strEACPROPKEY + " input").val("1");
          $("#eacmlsnum_" + strEACPROPKEY + " input").val(String(strEACMLSNUM));
        }
        else
          alert('File upload failed!\nPlease contact support on 1300 137 161.');
      }
    });
  });

  $("#update-salesperson").attr("href", "http://redsquare.eac.com.au/login.aspx?LID=" + getParameterByName("LID") + "&KID=" + getParameterByName("KID"));

  $("#lblcolor").val(($.cookie("headingcolor") != null ? $.cookie("headingcolor") : "000000"));
  $("#the-color-picker").css({ backgroundColor: "#" + ($.cookie("headingcolor") != null ? $.cookie("headingcolor") : "000000") });
  $("#color-example").css({ color: "#" + ($.cookie("headingcolor") != null ? $.cookie("headingcolor") : "000000") });

  $('#colorSelector').ColorPicker({
    color: '#' + $.cookie("headingcolor"),
    onShow: function (colpkr) {
      $(colpkr).fadeIn(500);
      return false;
    },
    onHide: function (colpkr) {
      $(colpkr).fadeOut(500);
      return false;
    },
    onChange: function (hsb, hex, rgb) {
      $('#colorSelector div').css('backgroundColor', '#' + hex);
      $('#color-example').css('color', '#' + hex);
      $('#lblcolor').text(hex);
      $('#lblcolor').val(hex);
      $.cookie("headingcolor", hex, { expires: 365 });
    }
  });

  $(".property-row[title]").tooltip({
    // tweak the position
    offset: [25, 0],
    // use the "slide" effect
    effect: 'slide',
    // customise transparency
    opacity: 1
    // add dynamic plugin with optional configuration for bottom edge
  }).dynamic({ bottom: { direction: 'down', bounce: true} });

  $("#lstFranchiseColors").change(function () {
    $("#lstFranchiseColors > option:selected").each(function () {
      var hex = $(this).val();
      $('#colorSelector div').css('backgroundColor', '#' + hex);
      $('#color-example').css('color', '#' + hex);
      $('#lblcolor').text(hex);
      $('#lblcolor').val(hex);
      $.cookie("headingcolor", hex, { expires: 365 });
    });
  });

  $("#lstFranchiseColors > option").each(function () {
    var hex = $.cookie("headingcolor");

    if ($(this).val() == hex) {
      $(this).attr("selected", "selected");
    }
  });

  /****************
  * Tabs code.    *
  ****************/
  $(".tab-content").hide(); //Hide all content
  $("ul.tabs li:first").addClass("active").show(); //Activate first tab
  $(".tab-content:first").show(); //Show first tab content

  $("ul.tabs li").click(function () {
    $("ul.tabs li").removeClass("active");
    $(this).addClass("active");
    $(".tab-content").hide();

    var activeTab = $(this).find("a").attr("href");
    $(activeTab).fadeIn();
    return false;
  });


  /**********************
  * Quick Search Code.  *
  **********************/
  var QuickSearchRequest;
  var OutsideResultsList = true;
  var CanSuggest = true;

  $("#quick-search-results ul li a").live("click", function () {
    $("#" + $(this).attr("id").split("|").slice(0, 1)).val($(this).attr("id").split("|").slice(-1));
    $("#quick-search-results").hide();

    return false;
  });

  $(".qs-tb").live("focus", function () {
    FocusQuickSearchTextBox($(this));
  });

  $(".qs-tb").live("blur", function () {
    if (OutsideResultsList) {
      $("#quick-search-results").html("");
      $("#quick-search-results").hide();
    }
  });

  function FocusQuickSearchTextBox(control) {
    $("#quick-search-results").width($(control).width() - 1);
    $("#quick-search-results").css("left", $(control).position().left + "px");
    $("#quick-search-results").css("top", $(control).position().top + 21 + "px");
  }

  $("#quick-search-results ul li").live("mouseover", function () {
    $("#quick-search-results ul li a").removeClass("selected");
    $(this).children().addClass("selected");

    QuickSearchLastSelected = $("#quick-search-results ul li").index(this);
    OutsideResultsList = false;
  }).live("mouseout", function () {
    $("#quick-search-results ul li a").removeClass("selected");
    OutsideResultsList = true;
  });

  $(".qs-tb").live("keydown", function (e) {
    // e.which: 8 = backspace, 9 = tab, 13 = enter, 17 = ctrl, 32 = space, 38 = up, 40 = down, 65 = a, 90 = z 109 = -, 222 = ', 48 = 0, 57 = 9
    var TheControlID = $(this).attr("id");

    if (QuickSearchRequest) {
      QuickSearchRequest.abort();
    }

    if (e.which == 17) {
      CanSuggest = false;
      window.setTimeout("CanSuggest = true", 50);
    }

    // Up or down arrow handling.
    if (e.which == 38 || e.which == 40) {
      if (e.which == 40) { // Down.
        if (QuickSearchLastSelected == -1) {
          $("#quick-search-results ul li a").removeClass("selected");
          $("#quick-search-results ul li:first a").addClass("selected");
          $(this).val($("#quick-search-results ul li:first a").attr("id").split('|').slice(-1));

          QuickSearchLastSelected = $("#quick-search-results ul li").index($("#quick-search-results ul li:first"));
        }
        else if (QuickSearchLastSelected == $("#quick-search-results ul li").length - 1) {
          $("#quick-search-results ul li a").removeClass("selected");
          $(this).val(QuickSearchTyped);
          QuickSearchLastSelected = -1;
        }
        else {
          QuickSearchLastSelected++;

          $("#quick-search-results ul li a").removeClass("selected");
          var theObj = $("#quick-search-results ul li").eq(new Number(QuickSearchLastSelected));
          $(theObj).children().addClass("selected");
          $(this).val($(theObj).children().attr("id").split('|').slice(-1));
        }
      }
      else { // Up.
        if (QuickSearchLastSelected == -1) {
          $("#quick-search-results ul li a").removeClass("selected");
          $("#quick-search-results ul li:last a").addClass("selected");
          $(this).val($("#quick-search-results ul li:last a").attr("id").split('|').slice(-1));

          QuickSearchLastSelected = $("#quick-search-results ul li").index($("#quick-search-results ul li:last"));
        }
        else if (QuickSearchLastSelected == 0) {
          $("#quick-search-results ul li a").removeClass("selected");
          $(this).val(QuickSearchTyped);
          QuickSearchLastSelected = -1;
        }
        else {
          QuickSearchLastSelected--;

          $("#quick-search-results ul li a").removeClass("selected");
          var theObj = $("#quick-search-results ul li").eq(new Number(QuickSearchLastSelected));
          $(theObj).children().addClass("selected");
          $(this).val($(theObj).children().attr("id").split('|').slice(-1));
        }
      }
    }
    else if (e.which == 13) { // Enter was pressed.
      $("#quick-search-results").hide();
    }
    else { // Something was typed, let's run the ajax side of things.
      $("#quick-search-results ul li a").removeClass("selected");
      QuickSearchLastSelected = -1;

      // Declare the variables.
      var t = "";
      var q = "";
      var qsub = "";
      var qst = "";
      var ResultsListHTML = "";
      var patt = /[^a-z\s'-]+/gi;

      // Set Suburb variables to pass through to ajax function.
      if ($(this).attr("id") == "txtSearchSuburb") {
        t = "sub";

        if (e.which == 8)
          q = qsub = QuickSearchTyped = $(this).val().substr(0, $(this).val().length - 1).toLowerCase();
        else
          q = qsub = QuickSearchTyped = $(this).val() + (e.which == 109 ? "-" : (e.which == 222 ? "'" : (e.which == 32 ? " " : String.fromCharCode(e.which).toLowerCase())));

        q = q.replace(patt, "");
        qsub = qsub.replace(patt, "");
        QuickSearchTyped = QuickSearchTyped.replace(patt, "");
      }

      // Set Street variables to pass through to ajax function.
      if ($(this).attr("id") == "txtSearchStreet") {
        t = "street";

        if (e.which == 8)
          q = qst = QuickSearchTyped = $(this).val().substr(0, $(this).val().length - 1).toLowerCase();
        else
          q = qst = QuickSearchTyped = $(this).val() + (e.which == 109 ? "-" : (e.which == 222 ? "'" : (e.which == 32 ? " " : String.fromCharCode(e.which).toLowerCase())));

        q = q.replace(patt, "");
        qst = qst.replace(patt, "");
        QuickSearchTyped = QuickSearchTyped.replace(patt, "");

        qsub = $("#txtSearchSuburb").val();
      }

      q = jQuery.trim(q);
      var r = new RegExp(q, "i");
      var SearchType = "15";

      // AJAX time.
      if (q != "" && ((e.which > 64 && e.which < 91) || e.which == 32 || e.which == 109 || e.which == 222 || e.which == 8) && CanSuggest) {
        QuickSearchRequest = $.ajax({
          type: 'POST',
          dataType: 'json',
          url: 'quick-search.aspx',
          data: [{ name: 's', value: SearchType },
                 { name: 'sub', value: qsub },
                 { name: 'street', value: qst },
                 { name: 't', value: t }
                ],
          success: function (obj) {
            if (obj.Results != 0) {
              ResultsListHTML = "<ul>";
              for (var i = 0, x = obj.Results.length; i < x; i++) {
                ResultsListHTML += "<li><a href=\"#\" id=\"" + TheControlID + "|" + obj.Results[i].result + "\">" + obj.Results[i].result.match(r) + "<strong>" + obj.Results[i].result.replace(r, "") + "</strong></a></li>";
              }
              ResultsListHTML += "</ul>";
              $("#quick-search-results").fadeIn(200);
            }
            else {
              $("#quick-search-results").fadeOut(200);
            }
            $("#quick-search-results").html(ResultsListHTML);
          }
        });
      }
      else if (q == "") {
        $("#quick-search-results").fadeOut(200);
        $("#quick-search-results").html(ResultsListHTML);
      }
    }
  });
});

var winRef=null;
var bShowSplashPage=true;
var oPopupWindow=null;

function KeyPropertyDescriptionKeyUp(field, maxlen) {
  if (field.value.length > maxlen) {
    alert('The text for the Property Description can not be more than ' + maxlen + ' characters.\n\nYour description has been truncated!');
		field.value = field.value.substring(0, maxlen);
	}
}

function KeyPropertyClick() {
	var controls = getElementsByName_iefix("input", "SelectedProperty");
	for (var i = 0; i < controls.length; ++i) {
	  if (controls[i].checked) {
	    checkOrUncheckFPMaps(true);
	    
	    var lastPropInd = getElementsByName_iefix("input", "LastKeyPropertyIndex")[0].value;
	    
      if (lastPropInd == "-1") { //there is no key property selected.
			  var controls2 = getElementsByName_iefix("input", "lblPropertyDescription");
			  if (typeof (controls2[i]) != "undefined") {
			    getElementsByName_iefix("input", "LastKeyPropertyIndex")[0].value = i;
			    getElementsByName_iefix("textarea", "txtKeyPropertyDescText")[0].value = controls2[i].value;
			  }

			  var controls3 = getElementsByName_iefix("input", "lblBeUnEnc");
			  if (typeof (controls3[i]) != "undefined") {
			    getElementsByName_iefix("input", "txtBedroomsUnEnc")[0].value = (controls3[i].value != "0" ? controls3[i].value : "");
			  }
			  var controls4 = getElementsByName_iefix("input", "lblBaUnEnc");
			  if (typeof (controls4[i]) != "undefined") {
			    getElementsByName_iefix("input", "txtBathroomsUnEnc")[0].value = (controls4[i].value != "0" ? controls4[i].value : "");
			  }
			  var controls5 = getElementsByName_iefix("input", "lblGaUnEnc");
			  if (typeof (controls5[i]) != "undefined") {
			    getElementsByName_iefix("input", "txtGargParkUnEnc")[0].value = (controls5[i].value != "0" ? controls5[i].value : "");
			  }
	    }
	    else {
	      if (lastPropInd != i) {
				  var result = confirm("The Property Description text will be changed if you change the selected Property.\n\nDo you wish to continue?");
					if (result) {
					  var controls2 = getElementsByName_iefix("input", "lblPropertyDescription");
					  if (typeof (controls2[i]) != "undefined") {
					    getElementsByName_iefix("textarea", "txtKeyPropertyDescText")[0].value = controls2[i].value;
					    getElementsByName_iefix("input", "LastKeyPropertyIndex")[0].value = i;
					  }

					  var controls3 = getElementsByName_iefix("input", "lblBeUnEnc");
					  if (typeof (controls3[i]) != "undefined") {
					    getElementsByName_iefix("input", "txtBedroomsUnEnc")[0].value = (controls3[i].value != "0" ? controls3[i].value : "");
					  }
					  var controls4 = getElementsByName_iefix("input", "lblBaUnEnc");
					  if (typeof (controls4[i]) != "undefined") {
					    getElementsByName_iefix("input", "txtBathroomsUnEnc")[0].value = (controls4[i].value != "0" ? controls4[i].value : "");
					  }
					  var controls5 = getElementsByName_iefix("input", "lblGaUnEnc");
					  if (typeof (controls5[i]) != "undefined") {
					    getElementsByName_iefix("input", "txtGargParkUnEnc")[0].value = (controls5[i].value != "0" ? controls5[i].value : "");
					  }
					}
					else {
					  controls[i].checked = false;
						controls[lastPropInd].checked = true;
					}
				}
			}
			break;
		}
	}	
}

function getElementsByName_iefix(tag, name) {   
	var elem = document.getElementsByTagName(tag);
	var arr = new Array();
	for(i = 0,iarr = 0; i < elem.length; i++) {
	  var att = new String(elem[i].getAttribute("name"));
	  var txt = new RegExp(name, "g");
		if(att.match(txt)) {
		  arr[iarr] = elem[i];
			iarr++;
		}
	}
	return arr;
}

function checkOrUncheckFPMaps(checker) {
  document.getElementById("chkIncludeCadastralMap").checked = checker;
  document.getElementById("chkIncludeAerialMap").checked = checker;
}

function clearKeyProp() {
	var result = confirm("The text in the Property Description field will be deleted if you clear the selected property.\n\nDo you wish to continue?")
	if (result) {
	  var controls = getElementsByName_iefix("input", "SelectedProperty");
		for (var nIdx = 0; nIdx < controls.length; nIdx++) {
		  controls[nIdx].checked = false;
		}
		getElementsByName_iefix("input", "LastKeyPropertyIndex")[0].value = -1;
		getElementsByName_iefix("input", "txtBedroomsUnEnc")[0].value = "";
		getElementsByName_iefix("input", "txtBathroomsUnEnc")[0].value = "";
		getElementsByName_iefix("input", "txtGargParkUnEnc")[0].value = "";
		getElementsByName_iefix("textarea", "txtKeyPropertyDescText")[0].value = "";
		document.getElementById("chkEstimatedSellingPrice").checked = false;
		
		checkOrUncheckFPMaps(false);
	}
}

function CheckKeyProperty() {
	var KeyPropertySelected=false;
	var controls = getElementsByName_iefix("input", "SelectedProperty");
	for (var nIdx = 0; nIdx < controls.length; nIdx++) {
		if(controls[nIdx].checked) {
		  KeyPropertySelected=true;
			getElementsByName_iefix("textarea", "txtKeyPropertyDescText").value = getElementsByName_iefix("input", "HiddenString").value;
			break;
	  }
  }
  if(!KeyPropertySelected) {
	  window.alert("Please select a Property before activating this option.");
	  document.getElementById("chkEstimatedSellingPrice").checked = false;
		checkOrUncheckFPMaps(false);
	}	
}

var iHighlighted = 0;

function setHighlightedValue() {
  var list = document.getElementById('resultsul');
  if (!list) { return false; }
  else {
    if (list.childNodes[iHighlighted-1] != null) {
      var re4 = new RegExp("<br>", "gi");
      var txtInput = list.childNodes[iHighlighted-1].innerHTML.split(re4);
      var re = new RegExp("<strong>", "gi");
      var re2 = new RegExp("</strong>", "gi");
      var txtPCDWorking = txtInput[1].split(re2);
      var txtPCD = txtPCDWorking[0].split(re);
      
      
      document.getElementById('txtSuburb').value = txtInput[0].replace(re, "").replace(re2, "");
      document.getElementById('txtPostCode').value = txtPCD[1];
      iHighlighted = 0;
      
      if (document.getElementById('txtSuburb').createTextRange) {
        var fieldRange = document.getElementById('txtSuburb').createTextRange();
        
        fieldRange.moveStart('character', document.getElementById('txtSuburb').value.length);
        fieldRange.collapse();
        fieldRange.select();
      }
      
      if (document.all) { document.getElementById('resultsul').style.visibility='hidden'; }
      else {
        document.getElementById('resultsul').style.visibility='hidden';
        document.getElementById('v').style.display='none';
      }
      
      window.setTimeout("document.getElementById('v').style.display='none'",300);
      return false;
    }
  }
}

function changeHighlight(key) {
  var list = document.getElementById('resultsul');
  
  if (!list) { return false; }
  
  var n
  
  if (key == 40) { n = iHighlighted + 1; }
  if (key == 38) { n = iHighlighted - 1; }
  
  if (n > list.childNodes.length) { n = list.childNodes.length; }
  
  if (n < 1) { n = 1; }
  
  setHighlight(n)
}

function setHighlight(n) {
  var list = document.getElementById('resultsul');
  
  if (!list) { return false; }
  
  if (iHighlighted > 0) { clearHighlight(); }
  
  iHighlighted = Number(n);
  list.childNodes[iHighlighted-1].className = 'as_highlight';
}

function clearHighlight() {
  var list = document.getElementById('resultsul');
  
  if (!list) { return false; }
  
  if (iHighlighted > 0) {
    list.childNodes[iHighlighted-1].className = '';
    iHighlighted = 0;
  }
}

function ajaxFunction(e) {
  if (document.getElementById('txtSuburb').value == '') { document.getElementById('v').style.display='none'; }
  
  var key = (window.event) ? window.event.keyCode : e.keyCode;
  var ARRUP = 38
  var ARRDN = 40
  
  switch(key) {
    case ARRUP:
      changeHighlight(key);
      break;
    case ARRDN:
      changeHighlight(key);
      break;
  }
  
  var xmlHttp;
  
  try { 
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
  }
  catch (e) {
    // Internet Explorer
    try {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
      try { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }
      catch (e) { alert("Your browser does not support AJAX!"); return false; }
    }
  }
  
  xmlHttp.onreadystatechange=function() {
    if(xmlHttp.readyState==4) {
      if (xmlHttp.responseText.indexOf('resultsul') != -1) {
        document.getElementById('v').innerHTML=xmlHttp.responseText;
        document.getElementById('v').style.display='block';
        document.getElementById('resultsul').style.visibility='visible';
      }
      else { document.getElementById('v').style.display='none'; }
    }
  }
  
  if (key != 38 && key != 40 && document.getElementById('txtSuburb').value != '' && document.getElementById('txtSuburb').value != 'Please enter at least one suburb, postcode or property ID.') {
    var qs = document.getElementById('txtSuburb').value;
    var qs2 = qs.replace("<", "").replace(">", "").replace("'", "''");
    
    xmlHttp.open("GET", "getPostCode.aspx?value=" + qs2, true)
    xmlHttp.send(null);
    
    iHighlighted = 0;
  }
}

function getSubs(e) {
  var key = (window.event) ? window.event.keyCode : e.keyCode;
  
  if (key == 38 || key == 40) { ajaxFunction(e); }
  else { ajaxFunction(e); }
}

function clearTimer() {
  if (typeof ajaxTimer != 'undefined') { window.clearTimeout(ajaxTimer); }
}


/**
 * Ajax upload
 * Project page - http://valums.com/ajax-upload/
 * Copyright (c) 2008 Andris Valums, http://valums.com
 * Licensed under the MIT license (http://valums.com/mit-license/)
 * Version 3.1 (24.04.2009)
 */

/**
 * Changes from the previous version:
 * 1. Fixed Safari 4 (Mac) upload problem
 * Special thanks to Lauren Russell, Mike, Steffen for finding what caused this bug
 * 2. Improved compatability with jquery ui.
 * Thanks to Vladimir Shushkov
 * 3. Fixed problems with Opera, but you can't use false as a response now.
 * 
 * For the full changelog please visit: 
 * http://valums.com/ajax-upload-changelog/
 */

(function(){
	
var d = document, w = window;

/**
 * Get element by id
 */	
function get(element){
	if (typeof element == "string")
		element = d.getElementById(element);
	return element;
}

/**
 * Attaches event to a dom element
 */
function addEvent(el, type, fn){
	if (w.addEventListener){
		el.addEventListener(type, fn, false);
	} else if (w.attachEvent){
		var f = function(){
		  fn.call(el, w.event);
		};			
		el.attachEvent('on' + type, f)
	}
}


/**
 * Creates and returns element from html chunk
 */
var toElement = function(){
	var div = d.createElement('div');
	return function(html){
		div.innerHTML = html;
		var el = div.childNodes[0];
		div.removeChild(el);
		return el;
	}
}();

function hasClass(ele,cls){
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
	if (!hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
	var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
	ele.className=ele.className.replace(reg,' ');
}

// getOffset function copied from jQuery lib (http://jquery.com/)
if (document.documentElement["getBoundingClientRect"]){
	// Get Offset using getBoundingClientRect
	// http://ejohn.org/blog/getboundingclientrect-is-awesome/
	var getOffset = function(el){
		var box = el.getBoundingClientRect(),
		doc = el.ownerDocument,
		body = doc.body,
		docElem = doc.documentElement,
		
		// for ie 
		clientTop = docElem.clientTop || body.clientTop || 0,
		clientLeft = docElem.clientLeft || body.clientLeft || 0,
		
		// In Internet Explorer 7 getBoundingClientRect property is treated as physical,
		// while others are logical. Make all logical, like in IE8.
		
		
		zoom = 1;
		if (body.getBoundingClientRect) {
			var bound = body.getBoundingClientRect();
			zoom = (bound.right - bound.left)/body.clientWidth;
		}
		if (zoom > 1){
			clientTop = 0;
			clientLeft = 0;
		}
		var top = box.top/zoom + (window.pageYOffset || docElem && docElem.scrollTop/zoom || body.scrollTop/zoom) - clientTop,
		left = box.left/zoom + (window.pageXOffset|| docElem && docElem.scrollLeft/zoom || body.scrollLeft/zoom) - clientLeft;
				
		return {
			top: top,
			left: left
		};
	}
	
} else {
	// Get offset adding all offsets 
	var getOffset = function(el){
		if (w.jQuery){
			return jQuery(el).offset();
		}		
			
		var top = 0, left = 0;
		do {
			top += el.offsetTop || 0;
			left += el.offsetLeft || 0;
		}
		while (el = el.offsetParent);
		
		return {
			left: left,
			top: top
		};
	}
}

function getBox(el){
	var left, right, top, bottom;	
	var offset = getOffset(el);
	left = offset.left;
	top = offset.top;
						
	right = left + el.offsetWidth;
	bottom = top + el.offsetHeight;		
		
	return {
		left: left,
		right: right,
		top: top,
		bottom: bottom
	};
}

/**
 * Crossbrowser mouse coordinates
 */
function getMouseCoords(e){		
	// pageX/Y is not supported in IE
	// http://www.quirksmode.org/dom/w3c_cssom.html			
	if (!e.pageX && e.clientX){
		// In Internet Explorer 7 some properties (mouse coordinates) are treated as physical,
		// while others are logical (offset).
		var zoom = 1;	
		var body = document.body;
		
		if (body.getBoundingClientRect) {
			var bound = body.getBoundingClientRect();
			zoom = (bound.right - bound.left)/body.clientWidth;
		}

		return {
			x: e.clientX / zoom + d.body.scrollLeft + d.documentElement.scrollLeft,
			y: e.clientY / zoom + d.body.scrollTop + d.documentElement.scrollTop
		};
	}
	
	return {
		x: e.pageX,
		y: e.pageY
	};		

}
/**
 * Function generates unique id
 */		
var getUID = function(){
	var id = 0;
	return function(){
		return 'ValumsAjaxUpload' + id++;
	}
}();

function fileFromPath(file){
	return file.replace(/.*(\/|\\)/, "");			
}

function getExt(file){
	return (/[.]/.exec(file)) ? /[^.]+$/.exec(file.toLowerCase()) : '';
}			

// Please use AjaxUpload , Ajax_upload will be removed in the next version
Ajax_upload = AjaxUpload = function(button, options){
	if (button.jquery){
		// jquery object was passed
		button = button[0];
	} else if (typeof button == "string" && /^#.*/.test(button)){					
		button = button.slice(1);				
	}
	button = get(button);	
	
	this._input = null;
	this._button = button;
	this._disabled = false;
	this._submitting = false;
	// Variable changes to true if the button was clicked
	// 3 seconds ago (requred to fix Safari on Mac error)
	this._justClicked = false;
	this._parentDialog = d.body;
			
	if (window.jQuery && jQuery.ui && jQuery.ui.dialog){
		var parentDialog = jQuery(self._button).parents('.ui-dialog-content');
		if (parentDialog.length){
			this._parentDialog = parentDialog[0];
		}
	}
					
	this._settings = {
		// Location of the server-side upload script
		action: 'upload.php',			
		// File upload name
		name: 'userfile',
		// Additional data to send
		data: {},
		// Submit file as soon as it's selected
		autoSubmit: true,
		// The type of data that you're expecting back from the server.
		// Html and xml are detected automatically.
		// Only useful when you are using json data as a response.
		// Set to "json" in that case. 
		responseType: false,
		// When user selects a file, useful with autoSubmit disabled			
		onChange: function(file, extension){},					
		// Callback to fire before file is uploaded
		// You can return false to cancel upload
		onSubmit: function(file, extension){},
		// Fired when file upload is completed
		onComplete: function(file, response) {}
	};

	// Merge the users options with our defaults
	for (var i in options) {
		this._settings[i] = options[i];
	}
	
	this._createInput();
	this._rerouteClicks();
}
			
// assigning methods to our class
AjaxUpload.prototype = {
	setData : function(data){
		this._settings.data = data;
	},
	disable : function(){
		this._disabled = true;
	},
	enable : function(){
		this._disabled = false;
	},
	// removes ajaxupload
	destroy : function(){
		if(this._input){
			if(this._input.parentNode){
				this._input.parentNode.removeChild(this._input);
			}
			this._input = null;
		}
	},				
	/**
	 * Creates invisible file input above the button 
	 */
	_createInput : function(){
		var self = this;
		var input = d.createElement("input");
		input.setAttribute('type', 'file');
		input.setAttribute('name', this._settings.name);
		var styles = {
			'position' : 'absolute'
			,'margin': '-5px 0 0 -175px'
			,'padding': 0
			,'width': '220px'
			,'height': '30px'								
			,'opacity': 0
			,'cursor': 'pointer'
			,'display' : 'none'
			,'zIndex' :  2147483583 //Max zIndex supported by Opera 9.0-9.2x 
			// Strange, I expected 2147483647					
		};
		for (var i in styles){
			input.style[i] = styles[i];
		}
		
		// Make sure that element opacity exists
		// (IE uses filter instead)
		if ( ! (input.style.opacity === "0")){
			input.style.filter = "alpha(opacity=0)";
		}
							
		this._parentDialog.appendChild(input);

		addEvent(input, 'change', function(){
			// get filename from input
			var file = fileFromPath(this.value);	
			if(self._settings.onChange.call(self, file, getExt(file)) == false ){
				return;				
			}														
			// Submit form when value is changed
			if (self._settings.autoSubmit){
				self.submit();						
			}						
		});
		
		// Fixing problem with Safari
		// The problem is that if you leave input before the file select dialog opens
		// it does not upload the file.
		// As dialog opens slowly (it is a sheet dialog which takes some time to open)
		// there is some time while you can leave the button.
		// So we should not change display to none immediately
		addEvent(input, 'click', function(){
			self.justClicked = true;
			setTimeout(function(){
				// we will wait 3 seconds for dialog to open
				self.justClicked = false;
			}, 3000);			
		});		
		
		this._input = input;
	},
	_rerouteClicks : function (){
		var self = this;
	
		// IE displays 'access denied' error when using this method
		// other browsers just ignore click()
		// addEvent(this._button, 'click', function(e){
		//   self._input.click();
		// });
				
		var box, dialogOffset = {top:0, left:0}, over = false;							
		addEvent(self._button, 'mouseover', function(e){
			if (!self._input || over) return;
			over = true;
			box = getBox(self._button);
					
			if (self._parentDialog != d.body){
				dialogOffset = getOffset(self._parentDialog);
			}	
		});
		
	
		// we can't use mouseout on the button,
		// because invisible input is over it
		addEvent(document, 'mousemove', function(e){
			var input = self._input;			
			if (!input || !over) return;
			
			if (self._disabled){
				removeClass(self._button, 'hover');
				input.style.display = 'none';
				return;
			}	
										
			var c = getMouseCoords(e);

			if ((c.x >= box.left) && (c.x <= box.right) && 
			(c.y >= box.top) && (c.y <= box.bottom)){			
				input.style.top = c.y - dialogOffset.top + 'px';
				input.style.left = c.x - dialogOffset.left + 'px';
				input.style.display = 'block';
				addClass(self._button, 'hover');				
			} else {		
				// mouse left the button
				over = false;
				if (!self.justClicked){
					input.style.display = 'none';
				}
				removeClass(self._button, 'hover');
			}			
		});			
			
	},
	/**
	 * Creates iframe with unique name
	 */
	_createIframe : function(){
		// unique name
		// We cannot use getTime, because it sometimes return
		// same value in safari :(
		var id = getUID();
		
		// Remove ie6 "This page contains both secure and nonsecure items" prompt 
		// http://tinyurl.com/77w9wh
		var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
		iframe.id = id;
		iframe.style.display = 'none';
		d.body.appendChild(iframe);			
		return iframe;						
	},
	/**
	 * Upload file without refreshing the page
	 */
	submit : function(){
		var self = this, settings = this._settings;	
					
		if (this._input.value === ''){
			// there is no file
			return;
		}
										
		// get filename from input
		var file = fileFromPath(this._input.value);			

		// execute user event
		if (! (settings.onSubmit.call(this, file, getExt(file)) == false)) {
			// Create new iframe for this submission
			var iframe = this._createIframe();
			
			// Do not submit if user function returns false										
			var form = this._createForm(iframe);
			form.appendChild(this._input);
			
			form.submit();
			
			d.body.removeChild(form);				
			form = null;
			this._input = null;
			
			// create new input
			this._createInput();
			
			var toDeleteFlag = false;
			
			addEvent(iframe, 'load', function(e){
				if (iframe.src == "about:blank"){						
					// First time around, do not delete.
					if( toDeleteFlag ){
						// Fix busy state in FF3
						setTimeout( function() {
							d.body.removeChild(iframe);
						}, 0);
					}
					return;
				}				
				
				var doc = iframe.contentDocument ? iframe.contentDocument : frames[iframe.id].document;

				// fixing Opera 9.26
				if (doc.readyState && doc.readyState != 'complete'){
					// Opera fires load event multiple times
					// Even when the DOM is not ready yet
					// this fix should not affect other browsers
					return;
				}
				
				// fixing Opera 9.64
				if (doc.body && doc.body.innerHTML == "false"){
					// In Opera 9.64 event was fired second time
					// when body.innerHTML changed from false 
					// to server response approx. after 1 sec
					return;				
				}
				
				var response;
									
				if (doc.XMLDocument){
					// response is a xml document IE property
					response = doc.XMLDocument;
				} else if (doc.body){
					// response is html document or plain text
					response = doc.body.innerHTML;
					if (settings.responseType == 'json'){
						response = window["eval"]("(" + response + ")");
					}
				} else {
					// response is a xml document
					var response = doc;
				}
																			
				settings.onComplete.call(self, file, response);
						
				// Reload blank page, so that reloading main page
				// does not re-submit the post. Also, remember to
				// delete the frame
				toDeleteFlag = true;				
				iframe.src = "about:blank"; //load event fired				 								
			});
	
		} else {
			// clear input to allow user to select same file
			this._input.value = '';						
		}
	},		
	/**
	 * Creates form, that will be submitted to iframe
	 */
	_createForm : function(iframe){
		var settings = this._settings;
		
		// method, enctype must be specified here
		// because changing this attr on the fly is not allowed in IE 6/7		
		var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
		form.style.display = 'none';
		form.action = settings.action;
		form.target = iframe.name;
		d.body.appendChild(form);
		
		// Create hidden input element for each data key
		for (var prop in settings.data){
			var el = d.createElement("input");
			el.type = 'hidden';
			el.name = prop;
			el.value = settings.data[prop];
			form.appendChild(el);
		}			
		return form;
	}	
};
})();

/**
 * jQuery.pulse
 * Copyright (c) 2008 James Padolsey - jp(at)qd9(dot)co.uk | http://james.padolsey.com / http://enhance.qd-creative.co.uk
 * Dual licensed under MIT and GPL.
 * Date: 05/11/08
 *
 * @projectDescription Applies a continual pulse to any element specified
 * http://enhance.qd-creative.co.uk/demos/pulse/
 * Tested successfully with jQuery 1.2.6. On FF 2/3, IE 6/7, Opera 9.5 and Safari 3. on Windows XP.
 *
 * @author James Padolsey
 * @version 1.11
 * 
 * @id jQuery.pulse
 * @id jQuery.recover
 * @id jQuery.fn.pulse
 * @id jQuery.fn.recover
 */
(function($){
    $.fn.recover = function() {
        /* Empty inline styles - i.e. set element back to previous state */
        /* Note, the recovery might not work properly if you had inline styles set before pulse initiation */
        return this.each(function(){$(this).stop().css({backgroundColor:'',color:'',borderLeftColor:'',borderRightColor:'',borderTopColor:'',borderBottomColor:'',opacity:1});});
    }
    $.fn.pulse = function(options){
        var defaultOptions = {
            textColors: [],
            backgroundColors: [],
            borderColors: [],
            opacityPulse: true,
            opacityRange: [],
            speed: 1000,
            duration: false,
            runLength: false
        }, o = $.extend(defaultOptions,options);
        /* Validate custom options */
        if(o.textColors.length===1||o.backgroundColors.length===1||o.borderColors.length===1) {return false;}
        /* Begin: */
        return this.each(function(){
            var $t = $(this), pulseCount=1, pulseLimit = (o.runLength&&o.runLength>0) ? o.runLength*largestArrayLength([o.textColors.length,o.backgroundColors.length,o.borderColors.length,o.opacityRange.length]) : false;
            clearTimeout(recover);
            if(o.duration) {
                setTimeout(recover,o.duration);
            }
            function nudgePulse(textColorIndex,bgColorIndex,borderColorIndex,opacityIndex) {
                if(pulseLimit&&pulseCount===pulseLimit) {
                    return $t.recover();
                }
                pulseCount++;
                /* Initiate color change - on callback continue */
                return $t.animate(getColorsAtIndex(textColorIndex,bgColorIndex,borderColorIndex,opacityIndex),o.speed,function(){
                    /* Callback of each step */
                    nudgePulse(
                        getNextIndex(o.textColors,textColorIndex),
                        getNextIndex(o.backgroundColors,bgColorIndex),
                        getNextIndex(o.borderColors,borderColorIndex),
                        getNextIndex(o.opacityRange,opacityIndex)
                    );
                });
            }
            /* Set CSS to first step (no animation) */
            $t.css(getColorsAtIndex(0,0,0,0));
            /* Then animate to second step */
            nudgePulse(1,1,1,1);
            function getColorsAtIndex(textColorIndex,bgColorIndex,borderColorIndex,opacityIndex) {
                /* Prepare animation object - get's all property names/values from passed indexes */
                var params = {};
                if(o.backgroundColors.length) {
                    params['backgroundColor'] = o.backgroundColors[bgColorIndex];
                }
                if(o.textColors.length) {
                    params['color'] = o.textColors[textColorIndex];
                }
                if(o.borderColors.length) {
                    params['borderLeftColor'] = o.borderColors[borderColorIndex];
                    params['borderRightColor'] = o.borderColors[borderColorIndex];
                    params['borderTopColor'] = o.borderColors[borderColorIndex];
                    params['borderBottomColor'] = o.borderColors[borderColorIndex];
                }
                if(o.opacityPulse&&o.opacityRange.length) {
                    params['opacity'] = o.opacityRange[opacityIndex];
                }
                return params;
            }
            function getNextIndex(property,currentIndex) {
                if (property.length>currentIndex+1) {return currentIndex+1;}
                else {return 0;}
            }
            function largestArrayLength(arrayOfArrays) {
                return Math.max.apply( Math, arrayOfArrays ); 
            }
            function recover() {
                $t.recover();
            }
        });
    }
})(jQuery);
/* The below code extends the animate function so that it works with color animations */
/* By John Resig */
(function(jQuery){
jQuery.each(['backgroundColor','borderBottomColor','borderLeftColor','borderRightColor','borderTopColor','color','outlineColor'],function(i,attr){jQuery.fx.step[attr]=function(fx){if(fx.state==0){fx.start=getColor(fx.elem,attr);fx.end=getRGB(fx.end)}fx.elem.style[attr]="rgb("+[Math.max(Math.min(parseInt((fx.pos*(fx.end[0]-fx.start[0]))+fx.start[0]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[1]-fx.start[1]))+fx.start[1]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[2]-fx.start[2]))+fx.start[2]),255),0)].join(",")+")"}});
function getRGB(color){var result;if(color&&color.constructor==Array&&color.length==3)return color;if(result=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color)){return[parseInt(result[1]),parseInt(result[2]),parseInt(result[3])]}if(result=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color)){return[parseFloat(result[1])*2.55,parseFloat(result[2])*2.55,parseFloat(result[3])*2.55]}if(result=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color)){return[parseInt(result[1],16),parseInt(result[2],16),parseInt(result[3],16)]}if(result=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color)){return[parseInt(result[1]+result[1],16),parseInt(result[2]+result[2],16),parseInt(result[3]+result[3],16)]}return colors[jQuery.trim(color).toLowerCase()]}
function getColor(elem,attr){var color;do{color=jQuery.curCSS(elem,attr);if(color!=''&&color!='transparent'||jQuery.nodeName(elem,"body")){break}attr="backgroundColor"}while(elem=elem.parentNode);return getRGB(color)};
var colors={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]};
})(jQuery);
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
function getParameterByName(name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

