/*
 * $Id: listing.js,v 1.34 2007/12/17 18:31:00 tcouch Exp $
 *
 * Listing related scripts
 */

/**
 * displays the business profile a listing
 * @param profId - the DOM id of the profile div for the listing
 * @param dispAdId - the DOM id of the display ad div for the listing.
 * @param listingId - the database id of the listing
 * @param image (optional) - URL to display ads image file, if provided
 *                           with maxWidth, display ads above business 
 *                           profile
 * @param maxWidth (optional) - maximum width of ads displaying area,
 *                              default to 490
 */
function showBusinessProfile(domListingId, listingId, image, maxWidth) {
    trackExpandBusinessProfile(listingId);
    
    if (image && maxWidth){
    	maxWidth = maxWidth ? maxWidth : 490;
	    var dispIdDiv = document.getElementById(domListingId + "_displayAd");	    
	    var img = dispIdDiv.getElementsByTagName("img")[0];
	    var newImg = new Image();
	    newImg.src = image;
	    img.onload = function() {
        	var styleName = newImg.width <= maxWidth ?
            	"displayAdVisible" : "displayAdVisibleScaled";            
       		dispIdDiv.className = styleName;
       		toggleDetails(domListingId + "_businessProfile", "profileVisible");
        }        
        img.src = image;
    }else{
    	toggleDetails(domListingId + "_businessProfile",
					"profileVisible",
		            domListingId + "_displayAd");
    }    
}

/**
 * displays the Display Ad of a listing
 * @param domListingId - the DOM id of the listing
 * @param image - the img file name.
 * @param listingId - the database id of the listing
 * @param maxWidth - The max width of display ad (default = 490px)
 */
function showDisplayAd(domListingId,  image, listingId, maxWidth) {
    maxWidth = maxWidth ? maxWidth : 490;
    trackExpandDisplayAd(listingId);
    var dispIdDiv = document.getElementById(domListingId + "_displayAd");
    var img = dispIdDiv.getElementsByTagName("img")[0];
    var offscreenImg = new Image();
    offscreenImg.src = image;
    img.onload = function() {
        var styleName = offscreenImg.width <= maxWidth ?
            "displayAdVisible" : "displayAdVisibleScaled";
        toggleDetails(domListingId + "_displayAd",
                         styleName,
                         domListingId + "_businessProfile");
    }
    if(img.src == image) {
        var styleName = offscreenImg.width <= maxWidth ?
	        "displayAdVisible" : "displayAdVisibleScaled";
        toggleDetails(domListingId + "_displayAd",
                         styleName,
                         domListingId + "_businessProfile");        
    } else {
	    img.src = image;
	}
}

/**
 * it toggles profile and display ad elements as only one of them can be visible
 *
 * @param showElementId - the DOM id of the element to show
 * @param showStyle - the css style that makes the element visible
 * @param hideElementId (optional)- if provided, the DOM id of the element that 
 *                                  must first be hidden.
 */
function toggleDetails(showElementId, showStyle, hideElementId) {
    var showElement = document.getElementById(showElementId);
    if (hideElementId){
	    var hideElement = document.getElementById(hideElementId);
	    if (hideElement) {
		    hideElement.className = "hiddenByDefault";
		}
	}
    if ( showElement.className == showStyle ) {
        showElement.className = "hiddenByDefault";
    } else {
        showElement.className = showStyle;
    }
}

function showMedia(id, type) {
    window.open(
        toAbsoluteUrl("media.do?id="+id+"&mediaType="+type),'',
        'resizable=yes,scrollbars=yes,height=520,width=750,toolbar=0,status=0,menubar=0');
}

/**
 * uncheck the compare checkboxes and empty the array.
 */
function clearAllCompareCheckboxes() {
    var index = 1;
    while ( true ){
        var ckBox = document.getElementById(genCkBoxName(index++));
        if ( ckBox == null ) {
            break;
        } else {
            ckBox.checked = false;
        }
    }
    __checkedListings__ = new Array();
}

/**
 * marks/checks compare checkboxes.
 */
function markAllCompareCheckboxes() {
    var index = 1;
    var listings = getCheckedListings();
    while ( true ){
        var ckBox = document.getElementById(genCkBoxName(index++));
        if ( ckBox == null ) {
            break;
        } else {
            ckBox.checked = true;
            var listingId = ckBox.value;
            if (! listings.contains(listingId) ){
                listings.push(listingId);
            }
        }
    }
}

/**
 * a convenience method that'll allow us to generate a checkbox id name given
 * its index in the listings.
 * @param index - the index
 */
function genCkBoxName(index) {
    return "listing_" + index + "_compareCkBox";
}


/**
 * Toggles compare checkboxes on/off _and_ adds/removes them from the list
 */
function toggleCompareCkBox(ckBox) {
    var listingId = ckBox.value;
    var listings = getCheckedListings();
    if ( ckBox.checked == true ){
        if (! listings.contains(listingId) ){
            if ( listings.length == 10 ) {
                alert ("Please compare upto 10 listings at a time");
                ckBox.checked = false;
                return false;
            }
            listings.push(listingId);
        }
    } else {
        listings.remove(listingId);
    }
}

/**
 * pops up a window for comparing atleast 2 but no more than 10 listings
 */
function compareListings() {

    var compareUrl = toAbsoluteUrl("compare.do");
    if ( getCheckedListings().length < 2 ) {
        alert("Please select at least 2 listings to compare.");
        return false;
    }
    compareUrl += "?ids=" + getCheckedListingsAsDelimitedString();
    window.open(compareUrl, "asCompare",
                "width=835,height=500,resizable=yes,scrollbars=yes,location=0,directories=0,toolbar=0,status=0,menubar=0");
}
/**
 * given a url, it appends a request parameter called 'checkedListings' with
 * ':' separated listingIds for values.
 * @param url - rel/abs url
 */
function appendListingIdsToUrl(url){
    if ( getCheckedListingsAsDelimitedString().length > 0 )
        return url + "&checkedListings=" + getCheckedListingsAsDelimitedString();
    return url;
}

/**
 * A utitlity function for collecting the listings into a ':' delimited string
 * which will be sent to the server as query param in which the caller provides
 * the param name.
 */
function getCheckedListingsAsDelimitedString() {
    var ret = "";
    var checkedListings = getCheckedListings();
    if ( checkedListings.length > 0 ) {
        var ret = checkedListings[0];
        for (i=1; i < checkedListings.length; i++ ){
               ret += ":" + checkedListings[i];
        }
    }
     return ret;
}

/**
 * A convenience method for accessing the global var holding onto checked
 * compare listing checkboxes.
 */
function getCheckedListings() {
    var myCheckedListings = __checkedListings__;
    return __checkedListings__;
}

function openWebsite(website,listingId) {
    window.open(website);
    trackCustomerWebsite(listingId);
}

/**
 * This function is used by clickToShow.tag. Takes the value from first child having ID "showOnClick"
 * and sets it's value to the parent (the clicked object). Cleans onclick event of element after first
 * run to deny multiple clicks. At the end calls passed in callback function.
 */
function showOnClick(clickedElement, callback) {
    for (i=0; i<clickedElement.childNodes.length; i++) {
        var child = clickedElement.childNodes[i];
        if (child.id=='showOnClick') {
            clickedElement.innerHTML = child.innerHTML;
            clickedElement.className = child.className;
            clickedElement.onclick='';
            clickedElement.style.cursor='auto';
            callback();
            break;
        }
    }
}
function openWindow(href) {
    window.open(toAbsoluteUrl(href),0,"");
}
