function updateShippingMethod(url, id)
{
    var now = new Date();
    var params = 'shippingMethodId='+ id + '&rt=' + now.getMilliseconds();
    createAjaxRequest(url, params, handleUpdateShippingMethod);
}

function countryChange(countryListBox)
{
    // get county element
    var county = $("*[name='county']").val();

    // get the index of the selected option

    var index = countryListBox.selectedIndex;
    // get the value of the selected option
    var countryCode = countryListBox.options[index].value;

//    var controllerUrl = getBaseUrl() + '/cart/update-states?countryCode=' + countryCode;
    var controllerUrl = getBaseUrl() + '/cart/update-states';
    var now = new Date();
    var params = 'countryCode='+ countryCode +'&county=' + county + '&rt=' + now.getMilliseconds();
    createAjaxRequest(controllerUrl, params, handleUpdateStatesMethod);
}

//@todo need to combine two methods below to one... element id should be parameter
function handleUpdateStatesMethod(response)
{
    var responseHtml = processHtmlResponse(response);

    if (COMMONS.isDefined(responseHtml) && responseHtml != "")
    {
        var insertSpan = $('#states');
        insertSpan.html(responseHtml);
    }
}

function handleUpdateShippingMethod(response)
{
    var responseHtml = processHtmlResponse(response);

    if (COMMONS.isDefined(responseHtml) && responseHtml != "")
    {
        var insertSpan = $('#totals');
        insertSpan.html(responseHtml);
    }
}

function closeLargeImage()
{
    if ($('#divLargeImageTable') !== null && $('#divLargeImageTable') !== undefined)
    {
	$('#divLargeImageTable').click(function(e)
	{
		X = e.pageX;
		Y = e.pageY;
		X1 = $("#idLargeImage").offset().left;
		Y1 = $("#idLargeImage").offset().top+20 ;
		X2 = X1 + $("#idLargeImage").outerWidth()-20;
		Y2 = Y1 + $("#idLargeImage").outerHeight();
		if(X<X1 || X>X2 || Y<Y1 || Y>Y2)
		{
	            $('#divLargeImageTable').css('display', 'none');
    updateLargeGallery(gallery.currentIndex);
		}

	});
    }

}

/**
 * Will center view large image window inside browser window
 * @param div
 */
function centerLargeImageTable(div)
{
    var marginTop = Math.round(($(window).height() - div.height()) / 2.0);
    if (marginTop < 0)
    {
        // if image is too big, use same padding as we have in the bottom 
        marginTop = div.css('marginBottom');
    }

    div.css('marginTop', marginTop);
}

function showLargeImage()
{
    switchImageCallback();

    var table = $('#divLargeImageTable');

    var div = $('#idLargeImage');
    if (COMMONS.isDefined(div))
    {
        table.css('display', '');
        centerLargeImageTable(div);
    }
}

function showLargeImage2(index)
{
    switchImageCallback();

    var table = $('#divLargeImageTable');

    var div = $('#idLargeImage');

    if (div !== null && div !== undefined)
    {
        updateLargeGallery(index);
        table.css('display', '');
        centerLargeImageTable(div);
    }
}

/**
 * This function startes zoomMode.
 * @param index index of current td (0 = first 'td')
 */
function showZoomedImage(index)
{
    // parse link of large image
    var elemA = $("#zoomImageHolder" + index).find("a");
    var hrefToSet = elemA.attr("href");

    var zooma = $('div#slideshow').zooma('slideshow', 'zoomBlock', hrefToSet);
    zooma.activate();

    globalZoom = zooma;
}

function handleProductDetailsImageClick() {
    if (zoomModeEnabled)
    {
        showZoomedImage(gallery.currentIndex);
        /* if zoom is enabled, we don't need to do anything */
        return;
    }
    if (enlargeModeEnabled)
    {
        showLargeImage2(gallery.currentIndex);
        /* if enlarge image is enabled, we don't need to do anything */
        return;
    }
}

/**
 * We will switch both galleries at the same, to open large gallery with correct image selected
 * @param index - index to set in large gallery
 */
function updateLargeGallery(index)
{
    // expected global variable 'galleryLarge'
    if (galleryLarge.currentIndex != index)
    {
        galleryLarge.goto(index);
    }
}

function switchImageCallback()
{
    if (typeof(globalZoom) != undefined && globalZoom != null)
    {
        globalZoom.deactivate();
    }
    updateLargeGallery(gallery.currentIndex);
}

function showProgressForPaymentDetails(divName, resourcePath)
{
    $(divName).css('display', '');
    $(divName + 'Hidden').css('background', 'url(https://' + self.location.hostname + resourcePath + '/images/bg.png) repeat 0 0');
    return true;
}

//deprecated (do not delete, because may be used in bespoke templates) - use showProgressForPaymentDetails(url, divName)
function showProgress()
{
    $('#divProgressBar').css('display', '');
    return true;
}

//deprecated (do not delete, because may be used in bespoke templates) - use showProgressForPaymentDetails(url, divName)
function showPaymentInProgress()
{
    $('#divPaymentProcessingProgress').css('display', '');
    return true;
}

function clearPaging(input)
{
    if(input.name == 'ppn')
    {
        input.value = 1;
    }
}

function updateProductPrice(url)
{
    var now = new Date();
    var params = $('#optForm').serialize();
    if (COMMONS.isDefined(params) && $.trim(params) != '')
    {
        params += '&rt=' + now.getMilliseconds();
    }
    createAjaxRequest(url, params, handleUpdateProductPrice);
}

function handleUpdateProductPrice(response)
{
    var responseText = processHtmlResponse(response);
    var result = JSON.parse(responseText);
    
    if (COMMONS.isDefined(result['priceData']))
    {
        var priceData = JSON.parse(result['priceData']);
        var price = priceData['price'];
        setHTML('product_price', price);
        if (COMMONS.isDefined(priceData['oldPrice']))
        {
            var oldPrice = priceData['oldPrice'];
            setHTML('was_price', oldPrice);
        }

        var stockInfo = priceData['stockInfo'];
        if (COMMONS.isDefined(stockInfo))
        {
            var purchaceEnabled = stockInfo['purchaseEnabled'];
            if (!purchaceEnabled)
            {
                $('#buy_button').removeClass().addClass("smallBtn opacity");
                $('#buy_button').attr('disabled', 'true');
            }
            else
            {
                $('#buy_button').removeClass().addClass("smallBtn");
                $('#buy_button').removeAttr('disabled');
            }

            var message = stockInfo['message'];
            if (COMMONS.isDefined(message))
            {
                setHTML('product_error', '<p class="error">' + message + '</p>');
            }
            else
            {
                setHTML('product_error', '');
            }
        }
    }
}

function getBaseUrl()
{
    if (window.location.pathname.substring(0,4) == '/cms')
    {
        return '/cms/preview';
    }

    if (window.location.pathname.substring(0,12) == '/engine/shop')
    {
        return '/engine/shop';
    }

    return '';

}
function getProductAttributeUrl(sku)
{
    return getBaseUrl() + '/get-product-attribute?sku=' + sku;
}

function getProductAttribute(sku, handleGetProductAttribute)
{
    var url = getProductAttributeUrl(sku);

    var now = new Date();
    var params = $('#optForm').serialize();
    if (COMMONS.isDefined(params) && $.trim(params) != '')
    {
        params += '&rt=' + now.getMilliseconds();
    }
    createAjaxRequest(url, params, handleGetProductAttribute);
}

function updateStateField(countryName, handleGetProductAttribute)
{
    var url = getBaseUrl() + '/get-country-states?countryName=' + countryName;

    var now = new Date();
    var params = $('#optForm').serialize();
    if (COMMONS.isDefined(params) && $.trim(params) != '')
    {
        params += '&rt=' + now.getMilliseconds();
    }
    createAjaxRequest(url, params, handleGetProductAttribute);
}

function switchLinkedProducts(url, cs)
{
    var now = new Date();
    var params = 'pid=' + $('#pid').val() + '&tabUID=' + $('#tabUID').val() + '&cs=' + cs + '&rt=' + now.getMilliseconds();
    createAjaxRequest(url, params, handleSwitchLinkedProducts);
}

function handleSwitchLinkedProducts(response)
{
    var responseHtml = processHtmlResponse(response);

    if (COMMONS.isDefined(responseHtml) && responseHtml != "")
    {
        var insertSpan = $('#linked_products');
        insertSpan.html(responseHtml);
    }
}

function setHTML(elementId, html)
{
    var insertSpan = $('#' + elementId);
    insertSpan.html(html);
}

function setValue(elementId, value)
{
    var element = $('#' + elementId);
    element.val(value);
}

