var FAQ = {
    openAnswer: function(answer, opener) {
        var answerId = this.getAnswerId(answer);
        var answerElem = $(answerId);
        var visible = Element.visible(answerId);
        if (visible) {
            Effect.toggle(answerId)
            this.visibleQuestion = this.opener = null;
            this.switchClasses(opener, 0);
        } else {
            if (null != this.visibleQuestion)
                Effect.toggle(this.visibleQuestion);
            if (null != this.opener)
                this.switchClasses(this.opener, 0);
            this.opener = opener;
            if (null != this.opener)
                this.switchClasses(this.opener, 1);
            this.visibleQuestion = answerId;
            //alert(answerElem.offsetWidth);
            //alert(answerElem.offsetWidth);
            Effect.toggle(answerId);
        }
    },
    getAnswerId: function(answer) {
        return 'faq_answer_' + answer;
    },
    switchClasses: function(elem, index) {
        var classNames = ['collapsed', 'expanded'];
        Element.removeClassName(elem, classNames[1 - index]);
        Element.addClassName(elem, classNames[index]);
    }
};

function getClassName(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(' ');
}

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.offClass = 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(this.offClass) >= 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');
        }
    },
    setSubmit: function() {
        $('submit').disabled = !$F('credit_card_terms_accepted');
    },
	t: function(symbol) {
		return (window.jsTranslations || {})[symbol] || symbol;
	}
};

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();
}

var TimePeriod = Class.create();
TimePeriod.prototype = {
    associatedForm: null,
    initialize: function(formName) {
        this.currentRequest = this.nextRequest = null;
        this.associatedForm = $(formName || 'filterForm');
    },
    namedPeriodChanged: function() {
        $('period_type_hc').checked = true;
        this.formChanged();
    },
    formChanged: function() {
        this.updateFromDates();
        this.callAjax();
    },
    updateFromDates:function(){
        if ($('period_type_tf') && $('period_type_tf').checked) {
            $('start_date').value = this.getFieldAsSQLDate("fromPeriod");
            $('end_date').value = this.getFieldAsSQLDate("toPeriod");
        }
    },
    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;
        $('start_date').value = this.getFieldAsSQLDate("fromPeriod");
        $('end_date').value = this.getFieldAsSQLDate("toPeriod");
        this.formChanged();
    },
    sortOrderChanged: function(sortOrder) {
        $('order_by').value = sortOrder;
        //    if($('period_type_tf')) {
        //        $('period_type_tf').checked = true;
        //        $('start_date').value = this.getFieldAsSQLDate("fromPeriod");
        //        $('end_date').value = this.getFieldAsSQLDate("toPeriod");
        //    }
        //    this.callAjax();
        this.formChanged();

    },
    buildRequest: function() {
        var delimiter = this.associatedForm.action.indexOf("?") > 0 ? "&" : "?";
        return this.associatedForm.action + delimiter + Form.serialize(this.associatedForm);
    },
    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');
        new Ajax.Request(request, { onComplete: this.ajaxCompleted.bind(this) });
    },
    ajaxCompleted: function() {
        this.currentRequest = null;
        if (this.nextRequest != null) {
            var request = this.nextRequest;
            this.nextRequest = null;
            this.callThisRequest(request);
        }
    },
	campaignChanged: function() {
		$("adgroup").value = "*";
		this.formChanged();
	}
}

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 providerEditor = {
    init: function() {
		var panamaIdentifier = $F('client_panama_identifier');
		var	splitted = panamaIdentifier.split("|");
		if (splitted.length == 4) {
			$("client_yahoo_master_acct").value = splitted[0];
			$("client_yahoo_acct").value = splitted[1];
			$("client_yahoo_login").value = splitted[2];
			$("client_yahoo_pass").value = splitted[3];
		}
		this.originalAdwords = $F('acting_client_email');
        this.aci = $F('aci');
	},
	checkCredentials: function() {
		var url = '/Tool/client-manager?zaction=checkLogin';
		var googleLogin = $F('acting_client_email');

        var googlePassword = $F('client_adwords_pass');
		var panamaIdentifier = $F('client_yahoo_master_acct') + "|" + $F('client_yahoo_acct') + "|" + $F("client_yahoo_login") + "|" + $F("client_yahoo_pass");
		if (googleLogin.length > 0 && googleLogin != this.originalAdwords) {
			url += "&adWordsLogin=" + encodeURIComponent(googleLogin) + "&adwordsPassword=" + encodeURIComponent(googlePassword);
		}
		url += "&panamaIdentifier=" + encodeURIComponent(panamaIdentifier);

        this.googleLogin  = googleLogin;
        this.panamaIdentifier = panamaIdentifier;

        new Ajax.Request(  url, { onSuccess: this.checkComplete.bind(this), onFailure: this.checkFailed.bind(this) });
		$('checkCredentials').disabled = true;
	},
	checkComplete: function(t) {
        var result = t.responseText.strip();
		eval("result = " + result);
		var	msg = [];
		if (this.googleLogin.length > 0 && this.googleLogin != this.originalAdwords && result['google'].length > 0) { msg[0] = "Google: " + result['google']; }
		if (this.panamaIdentifier.length > 4 && result['yahoo'].length > 0) { msg[msg.size()] = "Yahoo: " + result['yahoo']; }
		if (msg.size() == 0) {
	        new Ajax.Request("/manage/edit_providers?email="+encodeURIComponent(this.googleLogin)+"&panama_identifier="+ encodeURIComponent(this.panamaIdentifier)+"&aci="+this.aci);
		} else {
			alert(msg.join(", And "));
			$('checkCredentials').disabled = false;
		}
    },
	checkFailed: function() {
		alert('Sorry, did not work out perfectly, dit it???')
		$('checkCredentials').disabled = false;
	}
}


Ajax.Responders.register({onComplete: function() {
    jQuery('.tipsy').remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).appendTo(document.body);
    jQuery('a[title], div[title], span[title]').tipsy({gravity: 's', html: 'true'});
}});

