/**
 * CompareCounter.js
 * Provides the compare functionality on searchresults.jsp
 * This class uses the sliding doors background image technique instead of using a checkbox to allow for more than one state.
 * Dependencies: ATC.js, prototype.js
 */

// Create namespace for the class
ATC.createNamespace('ATC.cs.fyc.srl');

// Class CompareCounter
ATC.cs.fyc.srl.CompareCounter = function(instName, formID, storeVehiclesInID, rowIdBase, maxCount, imgFrameWidth, messageList, errorMessageText) {
    this.name = instName;                      //  The instanced nm
    this.formID = formID;                       //  Form ID
    this.storeInID = storeVehiclesInID;         //  Prefix of form field naming convention
    this.vehicleList = "";                      //  Default the list of vehicles
    this.rowID = rowIdBase;                     //  Prefix of listing row naming convention
    this.compareMaxCount = maxCount;            //  Maximum number of vehicles that can be compared
    this.compareImgFrameWidth = imgFrameWidth;  //  Width that the background image needs to move
    this.compareCount = 0;                      //  Default the count of vehicles selected to compare
    this.messages = messageList;                //  List of messages to be shown when a user selects a listing
    this.errorMessage = errorMessageText;       //  Error Message for when a user clicks on only one listing then compare
    this.fadeTime = 3000;                       //  Time in milliseconds for the messages to display before they fade out
};

// Count how many vehicles have been checked
ATC.cs.fyc.srl.CompareCounter.prototype.countVehicle = function(vehicleID) {
    var compareImgOffset = 0;
    if (this.compareCount < this.compareMaxCount && !this.checkInList(vehicleID)){
        this.addToList(vehicleID);
        compareImgOffset = this.compareCount * this.compareImgFrameWidth;
        this.move(vehicleID, compareImgOffset);
        this.showMessage(vehicleID, this.compareCount);
    } else if (this.checkInList(vehicleID)){
        this.removeFromList(vehicleID);
        this.move(vehicleID, compareImgOffset);        
    } else {
        this.showMessage(vehicleID, 4);
    }
};

// Change position of background image
ATC.cs.fyc.srl.CompareCounter.prototype.move = function(vehicleID, compareImgOffset) {
    var currentElem = $(this.rowID + vehicleID);
    currentElem.style.backgroundPosition = compareImgOffset + "px 0px";
};

// Check if the vehicle ID is already stored in the list
ATC.cs.fyc.srl.CompareCounter.prototype.checkInList = function(vehicleID) {
    if(this.vehicleList.indexOf(vehicleID) != -1){
        return true;
    } else {
        return false;
    }
};

// Add a vehicle ID to the list
ATC.cs.fyc.srl.CompareCounter.prototype.addToList = function(vehicleID) {
    var tmpFieldVal = this.vehicleList;
    if(tmpFieldVal.length > 0 && tmpFieldVal.indexOf(",") == tmpFieldVal.lastIndexOf(",")) tmpFieldVal = tmpFieldVal + ",";
    tmpFieldVal = tmpFieldVal + vehicleID;
    this.vehicleList = tmpFieldVal;
    this.compareCount++;
};

// Remove a vehicle ID from the list
ATC.cs.fyc.srl.CompareCounter.prototype.removeFromList = function(vehicleID) {
    var tmpFieldVal = this.vehicleList;
    var compareImgOffset = 0;
    tmpFieldVal = tmpFieldVal.replace(vehicleID,"");
    tmpFieldVal = tmpFieldVal.replace(",,",",");
    if(tmpFieldVal.substring(tmpFieldVal.length -1, tmpFieldVal.length) == ",") tmpFieldVal = tmpFieldVal.substring(0, tmpFieldVal.length -1);
    if(tmpFieldVal.substring(0, 1) == ",") tmpFieldVal = tmpFieldVal.substring(1, tmpFieldVal.length);
    this.vehicleList = tmpFieldVal;
    if (tmpFieldVal.length > 0){
        var vehicleIDs = tmpFieldVal.split(",");
        for (i=0;i<vehicleIDs.length;i++){
            compareImgOffset = (i + 1) * this.compareImgFrameWidth;
            this.move(vehicleIDs[i], compareImgOffset);
        }
    }
    this.compareCount--;
};

// If backbutton was used repopulate list
ATC.cs.fyc.srl.CompareCounter.prototype.populateFromForm = function() {
    var formFieldElem;
    for (i=0;i<this.compareMaxCount;i++){ 
        formFieldElem = $(this.storeInID + i);
        if(formFieldElem != null && formFieldElem.value != ""){
            this.addToList(formFieldElem.value);
            this.move(formFieldElem.value, (i + 1) * this.compareImgFrameWidth);
        }
    }
};

// Submit form and error checking
ATC.cs.fyc.srl.CompareCounter.prototype.compareCheck = function(buttonID) {
    var form = $(this.formID);
    var formFieldElem;
    var vehicleIDs = this.vehicleList.split(",");
    var total = vehicleIDs.length;    
    var currentElem = $(buttonID);
    var docBody = $$("body");
    var currentElemWidth = currentElem.getWidth();
    var newDiv = document.createElement("div");
    var newDivPos = Position.cumulativeOffset(currentElem);
    var errorMessage = this.errorMessage;
    
    // Default all form fields before they are populated - this is needed to handle the Firefox backbutton state
    for (i=0;i<this.compareMaxCount;i++){ 
        formFieldElem = $(this.storeInID + i);
        formFieldElem.value = "";
    }
    
    // Populate the form fields from the list
    for (i=0;i<total;i++){ 
        formFieldElem = $(this.storeInID + i);
        formFieldElem.value = vehicleIDs[i];
    }
    
    if(total < 2) {
        newDiv.innerHTML = errorMessage;
        newDiv.setAttribute("id", "message_" + buttonID); 
        docBody[0].appendChild(newDiv);
        var newDivID = $("message_" + buttonID);
        $(newDivID).setStyle({'position':'absolute', 'zIndex':'5', 'left':((newDivPos[0] + currentElemWidth) + 'px'), 'top':((newDivPos[1] - 5) + 'px'), 'display':'block', 'width':'200px', 'padding':'4px'});
        $(newDivID).addClassName('compare-help-pop');
        var newIframe = document.createElement("iframe");
        newIframe.setAttribute("id", "iframe_" + buttonID);
        newIframe.setAttribute("scrolling", "no");
        docBody[0].appendChild(newIframe);
        var newIframeID = $("iframe_" + buttonID);
        var newDivCurrentPos = Position.cumulativeOffset(newDivID);
        $(newIframeID).setStyle({'border': '0','position':'absolute', 'zIndex':'4', 'left':((newDivCurrentPos[0]) + 'px'), 'top':((newDivCurrentPos[1]) + 'px'), 'width': $(newDivID).getWidth(), 'height': $(newDivID).getHeight()});
        // Wait before removing the message 
        setTimeout(this.name + ".removeMessage('message_" + buttonID + "', 100, 0, 1000)", this.fadeTime);
        setTimeout(this.name + ".removeMessage('iframe_" + buttonID + "', 100, 0, 1000)", this.fadeTime);
    } else {
        form.submit();
    }
};

// Show message layer
ATC.cs.fyc.srl.CompareCounter.prototype.showMessage = function(vehicleID, showMessage) {
    var currentElem = $(this.rowID + vehicleID);
    var docBody = $$("body");
    var currentElemWidth = currentElem.getWidth();
    var newDiv = document.createElement("div");
    var newDivPos = Position.cumulativeOffset(currentElem);
    var Message = this.messages.split("|");    
    newDiv.innerHTML = Message[showMessage - 1];
    newDiv.setAttribute("id", "message_" + vehicleID); 
    docBody[0].appendChild(newDiv);
    var newDivID = $("message_" + vehicleID);
    $(newDivID).setStyle({'position':'absolute', 'zIndex':'5', 'left':((newDivPos[0] + currentElemWidth) + 'px'), 'top':((newDivPos[1] - 5) + 'px'), 'display':'block', 'width':'200px', 'padding':'4px'});
    $(newDivID).addClassName('compare-help-pop')
    // Wait before removing the message
    setTimeout(this.name + ".removeMessage('message_" + vehicleID + "', 100, 0, 1000)", this.fadeTime);
};

// Remove message layer
ATC.cs.fyc.srl.CompareCounter.prototype.removeMessage = function(id, opacStart, opacEnd, millisec) {
    //alert(this.iname);
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            this.timer(id,timer,speed);
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++)
            {
            this.timer(id,timer,speed);
            timer++;
        }
    }    
};

// Time between opacity change
ATC.cs.fyc.srl.CompareCounter.prototype.timer = function(id,timer,speed) {
    var triggerAtTimeout = this.name + ".changeOpac(" + i + ",'" + id + "')";
    setTimeout(triggerAtTimeout ,(timer * speed));
};

// Change Opacity
ATC.cs.fyc.srl.CompareCounter.prototype.changeOpac = function(opacity, id) {
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
    if(opacity == 0){
        var currentParent = $(id).parentNode;
        currentParent.removeChild($(id));
    }
};
