/* Start - Connect box */

function callNow() {
    if (isNumeric(document.callForm.contact.value) && document.callForm.contact.value.length == 10) {
        document.callForm.submit();
    } else {
        Element.update("callConnectError", "Enter a phone number to call this seller now");
    }
}

var sending = false;
function sendMessage() {
    if(!sending) {
        sending = true;

        document.sendNowImg.src = "/web/common/image/buttons/btn_sending.png";
        document.smsForm.submit();
    }
}

function changeContactLabel(r) {
    if (r.value == "SMS") {
        $("connectContact").innerHTML = "Mobile Number: ";
    } else if (r.value == "PHONE_CALL") {
        $("connectContact").innerHTML = "Phone Number: ";
    } else if (r.value == "EMAIL") {
        $("connectContact").innerHTML = "Email Address: ";
    }
}

function limitText(myField, limitCount, limitNum) {
    if (myField.value.length > limitNum) {
        myField.value = myField.value.substring(0, limitNum);
    } else {
        limitCount.value = limitNum - myField.value.length;
        // hack, hidden input to get count from
        document.getElementById('cleft').innerHTML = limitCount.value;
        // this is what actually display characters remaining
    }
}

/* End - Connect box */

// Set slideShowSpeed (milliseconds)
var slideShowSpeed = 3000;
// Duration of crossfade (seconds)
var crossFadeDuration = 2;

// Store the immage URL
var Pic = new Array();
// index array of pics
var ipic = 0;

// Store the caption of the image
var Desc = new Array();

// slideshow running or not
var running = true;
var t;
// timeout
var j = 0;


var preLoad = new Array();

// Run the slideshow
function runSlideShow() {
    if (running) {
        if (document.all) {
            document.images.SlideShow.style.filter = "blendTrans(duration=2)";
            document.images.SlideShow.style.filter = "blendTrans(duration=crossFadeDuration)";
            document.images.SlideShow.filters.blendTrans.Apply();
        }
        document.images.SlideShow.src = preLoad[j].src;
        document.getElementById('desc').innerHTML = Desc[j];
        document.getElementById('descAction').innerHTML = "<a href='javascript:stopSlideShow();'>STOP SLIDESHOW</a>";
        if (document.all) {
            document.images.SlideShow.filters.blendTrans.Play();
        }
        j = j + 1;
        if (j > (Pic.length - 1)) j = 0;
        t = setTimeout('runSlideShow()', slideShowSpeed);
    }
}

// stop the slideshow
function stopSlideShow() {
    running = false;
    document.getElementById('descAction').innerHTML = "<a href='javascript:startSlideShow();'>START SLIDESHOW</a>";
    showImageSec();
}

// restart the slideshow
function startSlideShow() {
    running = true;
    document.getElementById('descAction').innerHTML = "<a href='javascript:stopSlideShow();'>STOP SLIDESHOW</a>";
    runSlideShow();
    showImageSec();
}

// when the page loads, add the images to the array for the slideshow
function addImage(url, desc) {
    Pic[ipic] = url;
    Desc[ipic] = desc;
    preLoad[ipic] = new Image();
    preLoad[ipic].src = url;

    // increment the index
    ipic += 1;
}

// show an image in the main view
function showImage(idx) {
    stopSlideShow();
    document.images.SlideShow.src = preLoad[idx].src;
    document.getElementById('MainPic').href = preLoad[idx].src;
    document.getElementById('desc').innerHTML = Desc[idx];
    showImageSec();
}

function showEnlargedImage() {
    var imageUrl = document.images.SlideShow.src;
    var str = "" + imageUrl;

    var idx = str.indexOf('mid.', 0);
    if (idx > -1) {
        str = (str.substring(0, idx) + str.substring(idx + 3, str.length));
    }

    var jspPage = "/web/post/jsp/enlargedimage.jsp?src=" + str;

    window.open(jspPage, "Image", "status=no,toolbar=no,menubar=no,location=no,resize=yes,scrollbars=yes");
}

// when the page loads, put the first image in the viewer
function loadFirstImage() {
    if (Pic != null && Pic.length > 0) showImage(0);
}

// Show a media file that is NOT an image
function showMedia(src) {
    stopSlideShow();
    hideImageSec();

    document.getElementById('desc').innerHTML = "";

    // now write the viewer into the div:
    document.getElementById('mediaViewer').innerHTML = "<embed src='" + src + "' height='240' width='240px' autoplay='true' bgcolor='white' controller='true' enablejavascript=true pluginspage='http://www.apple.com/quicktime/download/' >";
}

// hide the image section
function hideImageSec() {
    document.images.SlideShow.src = "";
    document.images.SlideShow.width = 0;

}

// show the image section
function showImageSec() {
    document.getElementById('mediaViewer').innerHTML = "";
    document.images.SlideShow.width = 240;
}


//-------------------------------------------------//
// Google maps
//-------------------------------------------------//

var map = null;
var geocoder = null;

function addload() {
    try {
        if (GBrowserIsCompatible()) {
            map = new GMap2(document.getElementById("map"));
            map.addControl(new GSmallMapControl());
            geocoder = new GClientGeocoder();
            geocoder.getLatLng(address, function(point) {
                if (!point) {

                } else {
                    map.setCenter(point, 13);
                    var marker = new GMarker(point);
                    map.addOverlay(marker);
                }
            });
        }
    } catch(err) {
    }
}


// attach google event util:
/*************************************** Begin Post Reply related JS **************************************************/

/****** Begin Interface for UserRegistration And Login Overlay ******/

/**
 * called from register user overlay in search results. The overlay appears when the unregistered user
 * clicks add alert. Then, when the user types in registration info and clicks save, this method gets called.
 * If the save is successful, then the add alert page will be displayed, otherwise, the same page with error
 * messages will be displayed
 */
function saveUser() {
    var containerDiv = $("user_or_alert_or_login");
    var param = "a=su" + "&" + Form.serialize("frmRegisterUser");
    var xhr = new Ajax.Updater(containerDiv, "u.p",
    {
        parameters: param,
        onComplete: function() {
            Nifty("div#login,div#new_user", "normal");
        }
    });
}

/**
 * Shows the login page overlay
 */
function showLoginPage() {
    var containerDiv = $("user_or_alert_or_login");
    var param = "a=slpol" + "&pendingAlertId=" + $F('pendingAlertId');
    var xhr = new Ajax.Updater(containerDiv, "u.p",
    {
        parameters: param,
        onComplete: function() {
            Nifty("div#login,div#new_user", "normal");
        }
    });
}

/**
 * Shows the login page overlay
 */
function showStatsSmall(postId) {
    var containerDiv = $("stats_small");
    var linkDiv = $("statsLink");
    linkDiv.innerHTML = "Generating..."
    var param = "action=postStatsSmall" + "&postId=" + postId;
    var xhr = new Ajax.Updater(containerDiv, "activitylog.page",
    {
        parameters: param,
        onComplete: function() {

            linkDiv.innerHTML = "<a href=\"javascript:showStatsSmall(" + postId + ");\">Statistics</a>";

            //            Nifty("div#login,div#new_user","normal");
        }
    });
}


/**
 * executes the ajax login when the login request needs to be done from the search result page.
 * succesful login will return add alert page, and failure will return login page again so that the user
 * can correct the errors.
 */
function login() {
    var containerDiv = $("user_or_alert_or_login");
    var param = "a=al" + "&" + "from=POST_REPLY" + "&" + Form.serialize("frmLogin");
    var xhr = new Ajax.Updater(containerDiv, "u.p",
    {
        parameters: param,
        onComplete: function() {
            Nifty("div#login,div#new_user", "normal");
        }
    });
}

/****** Begin Interface for UserRegistration And Login Overlay ******/


/*************************************** End Post Reply related JS ****************************************************/


function dispute(index, replyId) {
    var param = "a=dispute&postReplyId=" + replyId;
    var xhr = new Ajax.Request("p.p",
    {
        parameters: param,
        onComplete: function() {
            Element.update("dispute" + index, "disputed");
        }
    });
}

function remove(index, postReplyId) {
    var containerDiv = $("pv_messagebox");
    var param = "a=rmvpr" + "&postReplyId=" + postReplyId;
    //Element.toggle(containerDiv);
    var xhr = new Ajax.Updater(containerDiv, "p.p",
    {
        parameters: param,
        onComplete: function() {
            //containerDiv.innerHTML = "This message was removed.";
        }
    });
}

function respond(index) {
    var containerDiv = $("respondBody_" + index);
    var txt = $("respondBodyText_" + index);
    if (containerDiv.style.display == 'block') containerDiv.style.display = 'none';
    else containerDiv.style.display = 'block';
    txt.focus();
}

function send(index, postReplyId, sellerId) {
    var containerDiv = $("pv_messagebox");
    var respondBodyText = $("respondBodyText_" + index);
    var param = "a=rspnd&text=" + escape(respondBodyText.value) + "&postReplyId=" + postReplyId + "&sellerId=" + sellerId;
    //Element.toggle(containerDiv);
    var xhr = new Ajax.Updater(containerDiv, "p.p",
    {
        parameters: param,
        onComplete: function() {
            //containerDiv.innerHTML = "Your reply was sent.";
        }
    });
}


// send the post to someone:
var lastType = 'r';
function sendPostLink(type, postId) {
    var containerDiv = $("sendToFriend");
    // ask if this is a click on the same type (sms / email) link
    var isSame = true;
    if(lastType=='r'){
        // first time click:
        lastType = type;
    } else{
        isSame = lastType == type;
    }    
    lastType = type;

    // ask if the div is already open:
    var isOpen = containerDiv.style.display != 'none';



    if (isOpen && isSame) {
        // close the div
        containerDiv.style.display = 'none';
    } else {
        // open the div:
        containerDiv.style.display = '';

        var param = "a=spls&type=" + type + "&postId=" + postId;
        //Element.toggle(containerDiv);
        var xhr = new Ajax.Updater(containerDiv, "p.p",
        {
            parameters: param,
            onComplete: function() {
                //containerDiv.innerHTML = "Your reply was sent.";
            }
        });
    }
}

function savePostLink(type, postId) {
    var containerDiv = $("sendToFriend");
    var dest = $("yourFriendEmail").value;

    var isEmail = type == 'e';
    var param = "a=splv&aj=aj&type=" + type + "&postId=" + postId +
                (isEmail ? "&yourEmail=" + escape($("yourEmail").value) : "") +
                "&yourName=" + escape($("yourName").value) +
                "&yourFriendEmail=" + escape($("yourFriendEmail").value) +
                "&yourMessage=" + escape($("yourMessage").value);

    //Element.toggle(containerDiv);
    var xhr = new Ajax.Updater(containerDiv, "p.p",
    {
        parameters: param,
        onComplete: function() {
            containerDiv.innerHTML = "Your message has been sent to " + dest;
        }
    });
}
