/* The initialization function.  This is called upon window.onload.
 */
function lightboxInit() {

    verifyActiveLightboxes();

    // set select dropdowns in the LB control panel
    var activeLbList = getActiveLightboxes();
    if ($("setLb1")) {
		for (i=0; i < 4; i++) {
			if (activeLbList[i]) {
				$("setLb" + (i+1)).value = activeLbList[i];
				if (toggle = $("lbActiveToggle_" + activeLbList[i]))
					toggle.className = "lb_active";
				debug("[LB] Setting setLb" + (i+1) + " to " + activeLbList[i]);
			}
		}
	}

	debug("Lightboxes initialized!");
}

var LB_INFO_MAP = new MfHashtable();  //this holds the image code to lightbox info
var ALL_LB_MAP = new MfHashtable();
var EXECUTE_AFTER_LIGHTBOX_VERIFY = [];
function verifyActiveLightboxes(){
    //this will validate and verify the active lightboxes
    //call this one time on load as it issues an ajax call
    LightboxListAction.execute({}, function displayLightboxes(response){
        var lbList = response.lightboxes;
        if ( lbList ) {
            var r = [];
            ALL_LB_MAP = new MfHashtable();
            for (var i =0; i < lbList.length; i++){
                ALL_LB_MAP.set(lbList[i].id,lbList[i].name);

                if ( lbList[i].active  ) {
                    r.push(lbList[i].id);
                }
            }
            if (r.length == 0 && lbList.length > 0){
                r.push(lbList[0].id); //put in the first one as active
            }
            debug("verifyActiveLightboxes setting active lightboxes to: "+r.join(","));
            setActiveLightboxes(r);
            //call everything that has been put in EXECUTE_AFTER_LIGHTBOX_VERIFY
            while(EXECUTE_AFTER_LIGHTBOX_VERIFY.length > 0){
                var f = EXECUTE_AFTER_LIGHTBOX_VERIFY.pop();
                f();
            }
            // configure the watermarked/non-watermarked storageType
            if( response.storageType != null){
                application.setStorageType(response.storageType);
            }

            userType = response.userType; 
        }
    });
}

function iconAddToLB(id, imagecode, elementID, optCurrentLightboxID) {

    //lbIcon : search/lb
    //bigThumbLbIcon : feature image
    //ssLbIcon : SimSearch
    var keyword;
    var rawSearchString;
    if ( elementID == "bigThumbLbIcon" ) {                
        keyword = DWRUtil.getValue("bigThumbKeyword");
        rawSearchString = DWRUtil.getValue("bigRawSearchString");
    } else if ( elementID == "ssLbIcon" ) {
        keyword = DWRUtil.getValue("ssKeyword");
        rawSearchString = DWRUtil.getValue("ssRawSearchString");
    } else if ( elementID == "lbIcon" ) {
        keyword = DWRUtil.getValue("querybox");
        rawSearchString = DWRUtil.getValue("rawSearchString");
    } else if ( elementID.slice(0,6) == "lbIcon" ) { // from lb
        keyword = DWRUtil.getValue(elementID+"Keyword");
        rawSearchString = DWRUtil.getValue(elementID+"rawSearchString");
    }
    if( keyword.containImageCode() ) {
        keyword = imagecode;
    }
    AddToLightbox.execute({'imagecode':imagecode,"id":id,'keyword':keyword,'rawSearchString':rawSearchString}, postIconAddToLB.curryAlt(id, imagecode, elementID, optCurrentLightboxID));
}

function postIconAddToLB(lightboxID, imagecode, iconDivPrefix, optCurrentLightboxID, response) {
    if ( response.ret_cd != 200 ) {
        alert ( i18n[response.ret_msg] );
        return;
    }
    
    if (LB_INFO_MAP.hasKey(imagecode)) {
        var ar = LB_INFO_MAP.get(imagecode);
        ar.push(lightboxID); //TODO implement check not to put it there twice
    } else {
        LB_INFO_MAP.set(imagecode, [lightboxID]);
    }

    if ( iconDivPrefix == "bigThumbLbIcon" ) {
        if ( imagecode == $("feature_image").getAttribute("imgCode") ) {
            drawLightboxAddRemoveIcons(iconDivPrefix,imagecode, optCurrentLightboxID);
        }
        if ( areWeInLightbox() ) {
            drawLightboxAddRemoveIcons("lbIcon"+imagecode,imagecode,optCurrentLightboxID);
        }
    } else {
        drawLightboxAddRemoveIcons(iconDivPrefix,imagecode, optCurrentLightboxID);
        if ( imagecode == $("feature_image").getAttribute("imgCode") ) {
            drawLightboxAddRemoveIcons("bigThumbLbIcon",imagecode, optCurrentLightboxID);
        }
    }
}

function iconRemoveFromLB(id, imagecode, elementID, optCurrentLightboxID) {
    var keywordDivId = elementID + "Keyword";

    if ( $(keywordDivId) ) {
        debug ( "iconRemoveFromLB keywordDivId value = " +  $(keywordDivId).value );
    }

    RemoveFromLightbox.execute({'imagecode':imagecode,"id":id}, postIconRemoveFromLB.curryAlt(id,imagecode,elementID, optCurrentLightboxID));
}

function postIconRemoveFromLB(lightboxID, imagecode, iconDivPrefix, optCurrentLightboxID, response) {
    if ( response.ret_cd != 200 ) {
        alert ( i18n[response.ret_msg] );
        return;
    }

    if (LB_INFO_MAP.hasKey(imagecode)) {
        var ar = LB_INFO_MAP.get(imagecode);
        var newAr = mfFilter(function(x) {return x != lightboxID}, ar);
        //debug("old ar:"+ar+" new ar:"+newAr+"   id:"+lightboxID);
        LB_INFO_MAP.set(imagecode, newAr);
    }

    if ( iconDivPrefix == "bigThumbLbIcon" ) {
        if ( imagecode == $("feature_image").getAttribute("imgCode") ) {
            drawLightboxAddRemoveIcons(iconDivPrefix,imagecode, optCurrentLightboxID);
        }
        if ( areWeInLightbox() ) {
            drawLightboxAddRemoveIcons("lbIcon"+imagecode,imagecode,optCurrentLightboxID);
        }
    } else {
        drawLightboxAddRemoveIcons(iconDivPrefix,imagecode, optCurrentLightboxID);

        if ( imagecode == $("feature_image").getAttribute("imgCode") ) {
            drawLightboxAddRemoveIcons("bigThumbLbIcon",imagecode, optCurrentLightboxID);
        }
    }
}

function initLightboxCheckboxes(){
    ELOCKS.set("LIGHTBOX_INIT");
    mfMap(function(item){
        if ( $("setActLbChk"+item) ) {
            $("setActLbChk"+item).checked = false;
        }
    },ALL_LB_MAP.getKeys());
    var currentActiveList = getActiveLightboxes();
    mfMap(function(item){
        if (new Number(item) <= 0) return; //do not do anything for zero
        if ( $("setActLbChk"+item) ){
            $("setActLbChk"+item).checked = true;
            setLbTableBackground(item,true);
        }
    },currentActiveList);
    ELOCKS.unset("LIGHTBOX_INIT");
}

function setActiveLBFromRadio(checkElement,lightboxID){

    if(ELOCKS.get("LIGHTBOX_INIT")) {
        return;
    }
    var currentActiveList = getActiveLightboxes();
    for(var i = 0; i < currentActiveList.length; i++){
        setLbTableBackground(currentActiveList[i],false);
    }

    var lbID = new Number(lightboxID);
    if(checkElement.checked ==true){
        jQuery.ajax({
        url: '/rpa/lb/default/'+ lbID + '.json/'+(new Date()).getTime(),
            success: function(response) {
                if ( response.status === "success" ) {
                    var ActiveList = [];
                    ActiveList.push( response.lightbox_id );
                    setActiveLightboxes(ActiveList);
                    setLbTableBackground(lbID,true);
                }
            }
        });
    }
}

//function activated by checkbox click on the page that lists lightboxes
//click/offclicking this will add/remove the lightbox from active lightboxes
function setActiveLBFromChk(checkElement,lightboxID){
    if(ELOCKS.get("LIGHTBOX_INIT")) {
        return;
    }
    var currentActiveList = getActiveLightboxes();
    var lbID = new Number(lightboxID);
    if(checkElement.checked ==true){
        //wants to add
        if(currentActiveList.length >= 4){
            alert(i18n.em_lightbox_four_already_active_simple);
            checkElement.checked = false;
        } else {
            currentActiveList.push(lbID);
            setActiveLightboxes(currentActiveList);
            setLbTableBackground(lbID,true);
        }
    } else {
        //wants to remove
        if(currentActiveList.length > 1){
            setLbTableBackground(lbID,false);
            var newList = [];
            for(var i = 0; i < currentActiveList.length; i++){
                if(currentActiveList[i] != lbID){
                    newList.push(currentActiveList[i]);
                }
            }
            setActiveLightboxes(newList);
        } else {
            alert(i18n.em_lightbox_at_least_one_active);
            checkElement.checked = true;
        }
    }
    resetTheActiveLBDropDown();
}

function resetTheActiveLBDropDown(){
    var activeLBs = getActiveLightboxes();
    for(var i=0; i < 4;i++){ //4 lbs
        var slObj = $("setLb"+(i+1));
        for(var j=0;j < slObj.options.length;j++){
            if(activeLBs[i] && new Number(slObj.options[j].value) == activeLBs[i]){
                slObj.options[j].selected=true;
            } else {
                slObj.options[j].selected=false;
            }
        }
    }

}

//function adds or removes yellow background from a lightbox table
//by adding or removing a classname
//if isSelected set to true the "lb_selected" class will be added
function setLbTableBackground(id,isSelected){
    if ( $("lbTableID"+id) ) {
        var oldName = new String($("lbTableID"+id).className);
        var nameAry = oldName.split(" ");
        //first filter out lb_selected
        nameAry = mfFilter(function(x){return ("lb_selected" != x)},nameAry);
        if(isSelected){
            nameAry.push("lb_selected");
        }
        var newName = "";
        for(var i = 0; i < nameAry.length;i++){
            if(i>0){
                newName += " ";
            }
            newName += nameAry[i];
        }
        $("lbTableID"+id).className = newName;
    }
}

