// Definition of some Page actions
var PAGE_ACTION_ADD_ROOM = "addroom";
var PAGE_ACTION_DESIGN_ROOM = "designroom";
var PAGE_ACTION_ADD_PRODUCT = "addp";

$(document).ready(function() { 
    $('#roomIdeasToggle').click(function() {
	    $('#roomIdeasBox').slideToggle(400);
	    $(this).toggleClass('showhideShow');
        return false;
    });
    
    $('#myProductsToggle').click(function() {			    
	    $('#myProductsBox').slideToggle(400);
		$(this).toggleClass('showhideShow');
        return false;
	});

	if ( $('#dialogueBox').length > 0 )
	    $('#dialogueBox').center({vertical: false});
	
	$('#a_showHiddenRooms').click( function() {
	    $('#span_hiddenRooms').show();
	    $('#span_showHiddenRooms').hide();
	    return false;
	});
	
	$('#a_showSurroundings').click( function() {
	    $('#span_hiddenSurroundings').show();
	    $('#span_showSurroundings').hide();
	    return false;
	});
	
	$('#a_showGoals').click( function() {
	    $('#span_hiddenGoals').show();
	    $('#span_showGoals').hide();
	    return false;
	});
	
	$('#a_showTags').click( function() {
	    $('#span_hiddenTags').show();
	    $('#span_showTags').hide();
	    return false;
	});
	
	$('.refinementTerm').mouseover( function() {
	    $(this).find('img').attr( 'src', '/media/icon_x_red.gif' );
	}).mouseout( function() {
	    $(this).find('img').attr( 'src', '/media/icon_x.gif' );
	});
	
    //call new window function on any <a> with the class of "newWin"
    $('a.newWin').click(function() {
       openWin(this.href);return false;
    });
		
    //rollover code for X close icon
    $('.btnClose').hover(function(){this.src='/media/btn_close_over.gif'},function(){this.src='/media/btn_close.gif'});
    $('.groupsIcon').hover(function() { this.src = '/media/icon_groups_on.gif' }, function() { this.src = '/media/icon_groups.gif' });
    
});

function TrimString(sInString) {
    sInString = sInString + ''; // to convert integer to string
    sInString = sInString.replace(/ /g, ' ');
    return sInString.replace(/(^\s+)|(\s+$)/g, '');
}

function isMyRoomRolloverExists() {
    return $('#MyRoomRolloverUp').length > 0;
}

function isMyRoomRolloverOpened() {
    var result = $.cookie("isMyRoomRolloverOpened");
    return (result == undefined || result == null) ? false : result == "true";
}

function userLogin(params, backurl) {
    //var prevUrl = (backurl == undefined || backurl == null ? escape(getPageUrlWithoutParams(['action'], "/ivillagewelcome")) : backurl);
    var prevUrl = (backurl == undefined || backurl == null ? escape(getPageUrlWithoutParams(['action'])) : backurl);

    // We need define the backurl because of return to previous page
    if (prevUrl.indexOf('signin') != -1 || prevUrl.indexOf('signup') != -1)
        backurl = '';
    else
        backurl = 'backurl=' + prevUrl;

    var params = (params == undefined || params == null ? '' : '&' + params);
    document.location.href = '/signin?' + backurl + params;
    return false;

    //
    // The NEXT code is not supported more in the new implementation.
    //

    params = (params != undefined ? params + '&' : '');
    tb_show('', '/signin?' + params + 'placeValuesBeforeTB_=savedValues&TB_iframe=true&height=540&width=650&modal=true');
}


function userSignup(params, backurl) {
    var prevUrl = (backurl == undefined || backurl == null ? escape(getPageUrlWithoutParams(['action'])) : backurl);
    // We need define the backurl because of return to previous page
    if (prevUrl.indexOf('signin') != -1 || prevUrl.indexOf('signup') != -1)
        backurl = '';
    else
        backurl = 'backurl=' + prevUrl;

    var params = (params == undefined || params == null ? '' : '&' + params);
    document.location.href = '/signup?' + backurl + params;
    return false;
}


function getPageUrlWithoutParams(params, url) {
    if( url == undefined ) url = document.location.href.replace('#', '');
    var keyValuePair;
    for (var index in params) {
        var param = params[index];
        if ($.query.get(param) != '') {
            keyValuePair = (param == 'action'
                    ? url.substring(url.indexOf(param)) // It is supposed the action is the last parameter in a Query string
                    : param + '=' + escape($.query.get(param))
                    );
            url = url.replace(keyValuePair, '');
            url = url.replace('?&', '?');
            url = url.replace('&&', '&');
            if (url.indexOf('?') == url.length - 1)
                url = url.substring(0, url.length - 1);
        }
    }

    return url;
}

$(window).resize(function () {
    //$('#TB_iframeContent').width($('#TB_iframeContent').width() + 1);
    //alert('resize');
});

function openDesignRoomPopup() {
    var selectedValue = $.cookie("selectedProductSet");
    
    if (selectedValue == null || selectedValue.toString() == '0')
        return;  
    
    // wait while currentProductSet will be loaded
    if (waitUntilProductsetIsReady("openDesignRoomPopup()")) return;

    if (!isApproved) {
        //userLogin('params=e3d_1');
        var backurl = escape(getPageUrlWithoutParams(['action']));
        var params = 'action=' + PAGE_ACTION_DESIGN_ROOM;
        var postBackerArg = { 'event': 'ContentChange', 'current': 'Login', 'target': 'Login', 'backurl': backurl, 'params': params };
        postBack(JSON.stringify(postBackerArg));
    }
    else {
        //step #1: Margin  
        //step #2: Min-Width, Min-Height limitations
        //step #3: Max-Width, Max-Height limitations
        var marginH = 33;
        var marginW = 25;

        var minW = 400;
        var minH = 400;

        var maxW = 1050;
        var maxH = 630;
        
        var windowW = $(window).width();
        var windowH = $(window).height();

        //step #1: Margin
        var popupW = windowW - marginW * 2;
        var popupH = windowH - marginH * 2;

        //step #2: Min-Width, Min-Height limitations
        if (popupW < minW)
            popupW = minW;

        if (popupH < minH)
            popupH = minH;        

        //step #3: Max-Width, Max-Height limitations
        if (popupW > maxW) {
            popupW = maxW;
        }
        if (popupH > maxH) {
            popupH = maxH;
        }
        
        if (popupW + marginW * 2 >= windowW)
            popupW = windowW - marginW * 2;
        if (popupH + marginH * 2 >= windowH)
            popupH = windowH - marginH * 2;

        ////step #1: Aspect ratio
        //var ratio = windowW / windowH;
        ////step #2: Margin
        //var popupW = windowW - marginW * 2;
        //var popupH = windowH - marginH * 2;
        ////step #3: Min-Width, Min-Height limitations
        //if (popupW < minW || popupH < minH) {
        //    var w = minW;
        //    var h = maxH; //Math.round(w / ratio);
        //    
        //    if( h < minH ) {
        //        h = minH;
        //        w = maxW; //Math.round(h * ratio);
        //    }

        //    popupW = w;
        //    popupH = h;
        //}
        ////step #4: Max-Width, Max-Height limitations
        //if (popupW > maxW || popupH > maxH) {
        //    var w = maxW;
        //    var h = Math.round(w / ratio);

        //    if (h > maxH) {
        //        h = maxH;
        //        w = //Math.round(h * ratio);
        //    }

        //    popupW = w;
        //    popupH = h;
        //}


//        var popupWidth = 914;
//        var popupHeight = 540;
//        var windowWidth = $(window).width();
//        var windowHeight = $(window).height();
//        var padding = 125;
//        //debugger;
//        if (popupWidth + padding * 2 < windowWidth) {
//            var newWidth = windowWidth - padding * 2;
//            popupHeight = popupHeight * newWidth / popupWidth;
//            if (popupHeight > windowHeight - 50) {
//                popupHeight = windowHeight - 50;
//            }
//            popupWidth = newWidth;
//        }
//        //make max-width 1050
//        var maxWidth = 1021;
//        if (popupWidth > maxWidth) {
//            var scale = popupWidth / popupHeight;
//            popupWidth = maxWidth;
//            popupHeight = Math.round(maxWidth / scale);
//        }

        tb_show('', '/shop/DesignRoom.aspx?params=e3d_1&placeValuesBeforeTB_=savedValues&amp;TB_iframe=true&amp;height=' + popupH + '&amp;width=' + popupW + '&amp;modal=true');
        var offset = windowH / 2 - popupH / 2;
        $('#TB_window').css('top', offset);
        $('#TB_window').css('margin-top', 0);
        //$('#TB_window').css('margin-top', offset); //.vAlign();
    }       
}

/*
    Desc: Waiting until downloading and intialization od ProductSet control will be completed.
    Result  = true if we need to wait
            = false if Productset is ready
*/
function waitUntilProductsetIsReady(callback) {
    if (!isMyRoomRolloverExists())
        return false;

    // wait while currentProductSet will be loaded
    var currentProductSet = $("#selectProductSet").get(0);
    if (!isMyRoomRolloverOpened() || currentProductSet == null || currentProductSet.options.length == 0
       || ($("#selectProductSet").val() == '0') || (($("#selectProductSet").val() != $.cookie("selectedProductSet")))) {
        setTimeout(callback, 100);  
        return true;
    }
    return false;
}

// Display/Hide Rollover Image
function changeLayer(id, display) {
    if (document.getElementById) {
        this.obj = document.getElementById(id).style;
        this.obj.display = display;
        return this.obj;
    }
    else if (document.all) {
        this.obj = document.all[id].style;
        this.obj.display = display;
        return this.obj;
    }
    else if (document.layers) {
        this.obj = document.layers[id];
        this.obj.display = display;
        return this.obj;
    }
}

function makeVisible(param) {
    new changeLayer(param, 'block');
}

function makeHidden(param) {
    new changeLayer(param, 'none');
}


function encodeUrl(url) {
    return encodeURI(url.replace('?', '').replace(' ', '_'));
}

function getTempDesignFlashUrl() {
    var result = "/";
    $.ajax({
        type: "POST",
        url: "/WebServices/Common.asmx/GetTempDesignFlashUrl",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({}),
        dataType: "json",
        async: false,
        success: function (json) {
            result = json.d;
        }
    });
    return result;
}

function getDesignaRoomUrl(id, predesigned) {
    var result = "/";
    $.ajax({
        type: "POST",
        url: "/WebServices/Common.asmx/GetDesignaRoomUrl",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ "id": id, "predesigned": predesigned }),
        dataType: "json",
        async: false,
        success: function (json) {
            result = json.d;
        }
    });
    return result;
}

function getCreateRoomWizardUrl(LastPageURI) {
    var result = "/";
    $.ajax({
        type: "POST",
        url: "/WebServices/Common.asmx/GetCreateRoomWizardUrl",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ "LastPageURI": LastPageURI }),
        dataType: "json",
        async: false,
        success: function (json) {
            result = json.d;
        }
    });
    return result;
}

//function getCreateRoomWizard2Url(LastPageURI, roomTypeId) {
//    var result = "/";
//    $.ajax({
//        type: "POST",
//        url: "/WebServices/Common.asmx/GetCreateRoomWizard2Url",
//        contentType: "application/json; charset=utf-8",
//        data: JSON.stringify({ "LastPageURI": LastPageURI, "roomTypeId": roomTypeId }),
//        dataType: "json",
//        async: false,
//        success: function (json) {
//            result = json.d;
//        }
//    });
//    return result;
//}

function GetDesignToolOnlyTargetHostURI(hostURL, targetURL) {
    var result = "/";
    $.ajax({
        type: "POST",
        url: "/WebServices/Common.asmx/GetDesignToolOnlyTargetHostUrl",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ "hostURL": hostURL, "targetURL": targetURL }),
        dataType: "json",
        async: false,
        success: function (json) {
            result = json.d;
        }
    });
    return result;
}

function getSearchProductsUrl(categoryId, query) {
    var result = "/";
    $.ajax({
        type: "POST",
        url: "/WebServices/Common.asmx/GetSearchProductsUrl",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ "categoryId": categoryId, "query": query }),
        dataType: "json",
        async: false,
        success: function (json) {
            result = json.d;
        }
    });
    return result;
}

function getWidgetUrl() {
    var result = "/";
    $.ajax({
        type: "POST",
        url: "/WebServices/Common.asmx/GetWidgetUrl",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ }),
        dataType: "json",
        async: false,
        success: function (json) {
            result = json.d;
        }
    });
    return result;
}

function getRoomIdeaUrl(id) {
    var result = "/";
    $.ajax({
        type: "POST",
        url: "/WebServices/Common.asmx/GetRoomIdeaUrl",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ "id": id }),
        dataType: "json",
        async: false,
        success: function (json) {
            result = json.d;
        }
    });
    return result;
}

function getOtherDomainWidgetUrl(domain) {
    var result = "/";
    $.ajax({
        type: "POST",
        url: "/WebServices/Common.asmx/GetOtherDomainWidgetUrl",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ 'domain': domain }),
        dataType: "json",
        async: false,
        success: function (json) {
            result = json.d;
        }
    });
    return result;
}

function isShow3DProductsChecked() {
    return $(".CheckBoxShow3D input").attr("checked") == true;
}


function userSignin(email, password, remember) {
    var result = false;
    $.ajax({
        type: "POST",
        url: "/WebServices/Common.asmx/UserLogin",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ "email": email, "password": password, "remember": remember }),
        dataType: "json",
        async: false,
        success: function (json) {
            result = (json.d == 'OK');
        }
    });
    return result;
}


function userSignup(username, email, password) {
    var result = false;
    $.ajax({
        type: "POST",
        url: "/WebServices/Common.asmx/UserSignup",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ "username": username, "email": email, "password": password }),
        dataType: "json",
        async: false,
        success: function (json) {
            result = (json.d == '');
        }
    });
    return result;
}


function mdiLoginUsingGigya(UID, timestamp, signature, email, password) {
    $.ajax({
        type: "POST",
        url: "/WebServices/Common.asmx/GigyaLogin",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ "UID": UID, "timestamp": timestamp, "signature": signature, "email": email, "password": password }),
        dataType: "json",
        async: false,
        success: function (json) {
            result = (json.d == 'true');
        }
    });
    return result;
}
