Ajax.Responders.register({
  onCreate: function() {
    if($('busy') && Ajax.activeRequestCount>0)
      Effect.Appear('busy',{duration:1,queue:'end'});
  },
  onComplete: function() {
    if($('busy') && Ajax.activeRequestCount==0)
      Effect.Fade('busy',{duration:1,queue:'end'});
  }
});

function removeAllChildren(e) {
    while (e.firstChild) {
        e.removeChild(e.firstChild);
    }
}


function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}

var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();
addEvent(window,'unload',EventCache.flush);

var rowRollover = {
	tipElements : ['tr', 'div'], // @Array: Allowable elements that can have the rollover effect
    onClass: 'ron',
    offClass: 'roff',
    init : function(options) {
    options = options || {};
    if (null != options['onClass']) this.onClass = options['onClass'];
    if (null != options['offClass']) this.onClass = options['offClass'];
    var parent = options['parent'] || document;
    var   i;
    for ( i=0; i <this.tipElements.length; i++ ) {
      var current = parent.getElementsByTagName(this.tipElements[i]);
      var curLen = current.length;
      for ( j=0; j<curLen; j++ ) {
        if (current[j].className.indexOf('roff') >= 0 && current[j].id != null) {
          addEvent(current[j],'mouseover',this.ron);
          addEvent(current[j],'mouseout',this.roff);
        }
      }
    }
  },
  ron: function(e) { rowRollover.doRowRollover(this, 1); rowRollover.callIfExists("rowTurnedOn", this); },
  roff: function(e){ rowRollover.doRowRollover(this, 0); rowRollover.callIfExists("rowTurnedOff", this); },
  doRowRollover: function(row, isInRow) {
    var className = row.className;
    var styles=[rowRollover.onClass, rowRollover.offClass];
    row.className = rowRollover.switchClassName(className, styles[1-isInRow], styles[isInRow]);
  },
  switchClassName: function(className, withName, withoutName) {
    if (null == className) className = "";
    var styles = className.split(" ");
    var found = false;
    for (var i = styles.length; --i >= 0; ) {
      if (styles[i] == withoutName) {
        styles[i] = withName;
        found = true;
      } else if (styles[i] == withName) {
        found = true;
      }
    }
    if (!found) styles.push(withName);
    return styles.join(' ');
  },
  callIfExists: function(funcName, parm1) {
    var f = rowRollover[funcName];
    if (null != f) {
      f(parm1);
    }
  }
}

function hideFlash() {
  var div = $('notice_div');
  if (div && Element.visible(div)) {
    Element.hide(div);
  }
}

var Utils = {
	redirectTo: function(url) {
      window.location.href = url;
  },
  now: function() {
      return new Date();
  },
	centerInWindow: function(element) {
		this.alignInWindow(element, 0.5, 0.33);
	},
	alignInWindow: function(element, horizontalRatio, verticalRatio) {
		var windowDimensions = Utils.windowDimensions();
		var elementDimensions = Element.getDimensions(element);

		var new_left = (windowDimensions.width - elementDimensions.width)*horizontalRatio + "px";
		var new_top = (windowDimensions.height - elementDimensions.height)*verticalRatio + "px";
		element.style.left = new_left;
		element.style.top = new_top;
	},
	windowDimensions: function() {
		return {
			height: this.window().innerHeight || document.body.clientHeight,
			width: this.window().innerWidth || document.body.clientWidth
		}
	},
	useMockWindow: function (w) {
		this.mockedWindow = w;
	},
	window: function() {
		return this.mockedWindow || window;
	},
  redirectIfConfirm: function(msg, url) {
    if (confirm(msg)) this.redirectTo(url);
  },
  deSnap: function() {
    var children = document.body.getElementsByTagName('a');
    var i;
    for (i = children.length; --i >= 0; ) {
      var a = children[i];
      if (!Element.hasClassName(a, 'snap_preview'))
        Element.addClassName(a, 'snap_nopreview');
    }
  }
};

Object.debug = function(obj) {
  var info = [];

  if(typeof obj in ["string","number"]) {
    return obj;
  } else {
    for(property in obj)
      if(typeof obj[property]!="function")
        info.push(property + ' => ' +
          (typeof obj[property] == "string" ?
            '"' + obj[property] + '"' :
            obj[property]));
  }

  return ("'" + obj + "' #" + typeof obj +
    ": {" + info.join(", ") + "}");
}

var Spinner = Class.create();

Spinner.prototype = {
  initialize: function(spinnerID) {
    if (null == spinnerID) spinnerID = 'spinner'; //  Default value
    this.spinner = $(spinnerID);
  },
  start: function() {
      Element.show(this.spinner);
  },
  startAndDisable: function(button2Disable) {
    if (null == button2Disable) button2Disable = 'submit';
    this.disabledButton = $(button2Disable);
    this.disabledButton.disabled = true;
    this.start();
  },
  stop: function() {
    Element.hide(this.spinner);
    if (null != this.disabledButton) this.disabledButton.disabled = false;
    this.disabledButton = null;
  }
}

var logger = null;
function startLogging() {
  logger = log4javascript.getLogger("main");
  var popUpAppender = new log4javascript.PopUpAppender();
  var popUpLayout = new log4javascript.PatternLayout("%d{HH:mm:ss} %-5p - %m%n");
  popUpAppender.setLayout(popUpLayout);
  logger.addAppender(popUpAppender);new log4javascript.PopUpAppender();
}

TimePeriod = Class.create();
TimePeriod.prototype = {
  initialize: function(baseURL, extras) {
    this.baseURL = baseURL;
    this.currentPage = 1;
    this.currentRequest = null;
    this.sortOrder = '';
    this.perPage = null;
    this.displayFilter = null;
    this.dateFields = null;
    this.extras = {};
    Object.extend(this.extras, extras || {});
    this.nextRequest = null;
  },
  useAjax: true,
  namedPeriodChanged: function() {
    $('period_type_hc').checked = true;
    this.dateFields = '&named_period=' + $F('namedPeriods');
    this.callAjax();
  },
  getFieldAsSQLDate: function(field) {
    var date = Date.parseDate($F(field), timeBoxDateFmt);
    return "" + date.getFullYear() + "-" + (1 + date.getMonth()) + "-" + date.getDate();
  },
  toFromChanged: function() {
    $('period_type_tf').checked = true;
    this.dateFields = '&start_date=' + this.getFieldAsSQLDate('fromPeriod') + "&end_date=" + this.getFieldAsSQLDate("toPeriod");
    this.callAjax();
  },
  rowsPerPageChanged: function(perPage) {
    this.perPage = perPage;
    this.currentPage = 1;
    this.callAjax();
  },
  sortOrderChanged: function(sortOrder) {
    this.sortOrder = sortOrder;
    this.callAjax();
  },
  currentPageChanged: function(newPage) {
    this.currentPage = newPage;
    this.callAjax();
  },
  filterChanged: function(newFilter) {
    this.displayFilter = newFilter;
    this.callAjax();
  },
  changeExtra: function(key, value) {
    this.extras[key] = value;
    this.callAjax();
  },
  buildRequest: function() {
    var request = this.baseURL;
    var first = request.indexOf('?') == -1 ? '?' : '&';
    if (null != this.perPage)
      request += first + 'per_page=' + this.perPage;
    else if (first == '?')
      request += '?1'
    request += '&order_by=' + encodeURI(this.sortOrder);
    request += '&page=' + this.currentPage;
    if (null != this.displayFilter)
      request += '&display_filter=' + this.displayFilter;
    if (null != this.dateFields) request += this.dateFields;
    for (var extra in this.extras) {
      var val = this.extras[extra];
      if (val != null)
        request += '&' + extra + '=' + encodeURI(this.extras[extra]);
    }
    return request;
  },
  callAjax: function() {
    var request = this.buildRequest();
    if (request == this.currentRequest) { this.nextRequest = null; return; }
    if (this.currentRequest != null) {
      this.nextRequest = request;
      return;
    }
    this.callThisRequest(request);
  },
  callThisRequest: function(request) {
    this.currentRequest = request;
//    Element.show('periodSpinner');
    if (this.useAjax) {
      new Ajax.Request(request, { onComplete: this.ajaxCompleted.bind(this) } );
    } else {
      var element = document.createElement('script');
      element.type = 'text/javascript';
      element.src = request;
      document.getElementsByTagName('head')[0].appendChild(element);
    }
  },
  ajaxCompleted: function() {
    this.currentRequest = null;
    if (this.nextRequest != null) {
      var request = this.nextRequest;
      this.nextRequest = null;
      this.callThisRequest(request);
    }
  }
}

Element['swapClassName'] = function(element, className2Add, className2Remove) {
  if (!(element = $(element))) return;
  return Element.classNames(element).swap(className2Add, className2Remove);
}

Element.ClassNames.prototype['swap']= function(classNameToAdd, classNameToRemove) {
  if (!this.include(classNameToRemove) && this.include(classNameToAdd)) return;
  this.set(this.select(function(className) {
    return className != classNameToRemove;
  }).toArray().concat(classNameToAdd).join(' '));
}

//Ajax.InPlaceEditorWithValue = Class.create();
//Object.extend(Object.extend(Ajax.InPlaceEditorWithValue.prototype,
//                            Ajax.InPlaceEditor.prototype), {
//  getText: function() {
//    return this.editableText || this.element.innerHTML;
//  },
//  setText: function(text) {
//    this.editableText = text;
//  }
//});

var adwordsChecker = {
    passwordField: "prospect_account_password",
    loginField: "prospect_account_login",
    valid: false,
    nameOrPasswordChange: function() {
      this.valid = false;
      var password = $F(adwordsChecker.passwordField);
      var login = $F(adwordsChecker.loginField);
      if (adwordsChecker.nameChecker.errors == 0 &&
            adwordsChecker.passwordChecker.errors == 0 &&
            password != "" && login != "") {
        adwordsChecker.urlChecker.extras["google_login"] = login;
        adwordsChecker.urlChecker.extras["password"] = password;
        adwordsChecker.urlChecker.callAjax();
//        console.log(adwordsChecker.urlChecker);
      }
    },
    setFields: function(f1,f2, checkUrl){
      this.nameChecker = f1;
      this.passwordChecker = f2;
      this.urlChecker = new TimePeriod(checkUrl);
      this.urlChecker.useAjax = false;
    },
    requestComplete: function(result) {
      this.urlChecker.ajaxCompleted();
      this.valid = result == 'OK';
      if (this.valid)
        Element.hide('google_verification_response');
      else
        Element.show('google_verification_response');
    }
}

