// submit to url and draw the result back to a div or a facebox
function ajaxCall (divToUpdate, title,  formName, urlToCall) {

    var $form = $('#' + formName);

    if (formName == null) {
        $.ajax({
           url: urlToCall,
            type: 'get',
            dataType: 'text',
            success: function(data, status, response) {
               successCallBack( divToUpdate, title, response.responseText );
            },
            complete: function(data) {
            },
            error: function(data) {
                alert('Error encountered. Please try again.');
            }
        });

    } else {

        var params = $form.serialize();

        $.ajax({
            url: urlToCall,
            type: 'post',
            dataType: 'text',
            data: params,
            success: function(data, status, response) {
                successCallBack( divToUpdate, title, response.responseText );
            },
            complete: function(data) {
            },
            error: function(data) {
                alert('Error encountered. Please try again.');
            }

        });
    }
}

function successCallBack( divToUpdate, title, contentData ) {

   if( divToUpdate == "facebox" ) {
       $.facebox( contentData );
   } else {
       $('#' + divToUpdate).html(contentData);
   }

   if(title != '')
        setFaceboxTitle("<h3>" + title + "</h3>");

}



function composeReview()
{
	ajaxCall('popupContent', 'Write a Comment ..', 'revform', '/action/public/writeReview.htm?reviewMode=compose');
}

function popReviewModal(id)
{
   ajaxCall('facebox', 'Write a Comment ..', 'revform', '/action/public/writeReview.htm?listingId=' + id + '&reviewMode=compose');
}

function previewReview()
{
	ajaxCall('popupContent', 'Preview your Comment before Submitting..', 'revform', '/action/public/writeReview.htm?reviewMode=preview');
}

function submitReview()
{
	if($('#origComment').val()==null || $('#origComment').val()=="")
	{
		ajaxCall('popupContent', 'Please correct the Error ..', 'revform', '/action/public/writeReview.htm?reviewMode=error');
		return;
	}

    ajaxCall('popupContent', 'Thanks for the Feedback ..', 'revform', '/action/member/submitReview.htm?reviewMode=success');
    // update the parent's review section under the modal screen

}

function addLinkCategory(){
	ajaxCall('popupContent', 'Link More Categories',  null, '/action/member/manageListing.htm?addCategory=1&cat=' + $('#category').val() + "&listing=" + $('#listingId').val() );
}

function viewLinkCategories(){
	ajaxCall('facebox', 'Link More Categories',  null, '/action/member/manageListing.htm?viewCategories=1'  + "&listing=" + $('#listingId').val() );
}

function replaceListingPhoto(){
	ajaxCall('facebox', 'Upload More Photos',  null, '/action/member/manageImage.htm?rep=1&editListingImage=1&listId=' +  $('#listingId').val());
}
	
function replaceProfilePhoto(){
	ajaxCall('facebox', 'Replace Profile Photo', null, '/action/member/manageImage.htm?rep=1&editProfileImage=1&userId=' + $('#userId').val());
}

var updater = null;
var ctr = 0;

// main function for upload monitoring
function monitorFileUpload() {
    try {
        // get upload status

        updater = $.PeriodicalUpdater('/upload', {
            method: 'get',          // method; get or post
            data: '',               // array of values to be passed to the page - e.g. {name: "John", greeting: "hello"}
            minTimeout: 200,       // starting value for the timeout in milliseconds
            maxTimeout: 400,       // maximum length of time between requests
            multiplier: 2,          // the amount to expand the timeout by if the response hasn't changed (up to maxTimeout)
            type: 'text',           // response type - text, xml, json, etc.  See $.ajax config options
            maxCalls: 0,            // maximum number of calls. 0 = no limit.
            autoStop: 0             // automatically stop requests after this many returns of the same data. 0 = disabled.
        }, function(data) {
                if (data.length > 1) {
//                    $('#successMsg').css({'visibility':'visible'});
                    $('#uploadStatusDiv').css({'visibility':'visible'});
                    $('#uploadStatusDiv').html("<img src='/images/loading.gif' style='height:15px; width:15px' />" + '<span> Uploading... please wait.. </span>');
//                    $('#submitImage').css({'display':'none'});
                } else {
                	ctr++;
                	if(ctr>5) {
                		handleUploadFinished();
                	}
                }
        });

    } catch(e) {
        alert('monitorFileUpload() failed, reason: ' + e);
    } finally {
    }
    return false;
}

// executes function after page loaded
function addLoadEvent(func) {

    var oldonload = window.onload;

    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            oldonload();
            func();
        }
    }
}

// this function will be executed after "target" IFRAME content changed
function handleUploadFinished() {

    // stop updater manually
    if ( updater != null && typeof updater != 'undefined') {
        updater.stop();
        updater = null;
    }
    $('#uploadStatusDiv').html("Successfully uploaded your photo..");

    ctr = 0;
}

// observe IFrame object for "load" event to stop AJAX updater
function observeFormSubmit() {
    // add event to observe upload target
    if ( $('#uploadTrg') != null && typeof $('#uploadTrg') != 'undefined') {
        $('#uploadTrg').load( function(data){
           handleUploadFinished();
        });
    }
}

function showListPicUploadMsg(msg) {
    var listId = $('#listingId').val();
    ajaxCall('uploadImage', '', null, '/action/member/manageImage.htm?editListingImage=1&listId=' + listId + '&msg=' + msg);
}

function showUserPicUploadMsg(msg) {
		var userId = $('#userId').val();
		ajaxCall('uploadImage', '',null, '/action/member/manageImage.htm?editProfileImage=1&userId=' + userId + '&msg=' + msg);
    $('#uploadStatusDiv').html("Uploaded Successfully");
}

function facebookLogin() {

    var top = (getPageHeight() - 300 ) / 2;
    var left = Math.floor(($(window).width() - 550) / 2);
    left = left > 0 ? left : 0;

    if ($.browser.msie) {

        var w = 800 / 1;
        var h = 500 / 1;
        var win = window.open("/action/public/fblogin.htm", "FacebookLogin", 'width=800, height=600');
        win.resizeTo(w, h);
        win.moveTo(top, left);
        win.focus();

    } else {
        window.showModalDialog("/action/public/fblogin.htm", "", "dialogWidth:800px; dialogHeight:500px; dialogLeft:" + left + "px; dialogTop: " + top + "px; ");
        window.location.replace("/yourbox/profile.htm")
    }
}


function getPageHeight() {
    var windowHeight;
    if (self.innerHeight) {    // all except Explorer
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowHeight = document.body.clientHeight;
    }
    return windowHeight
}

function checkCatCodeDuplicate(field){}
function checkCatNameDuplicate(field){}



// add event handler only after page loaded
addLoadEvent(observeFormSubmit);




