﻿function ShowUserControl(path, selector, width) {
    BlockUI();
    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        url: '/website/cms/CMSService.asmx/GetUserControl',
        data: '{"path": "' + path + '"}',
        dataType: 'json',
        success:
        function(msg) {
            if (msg.d != '-1') {
                $.unblockUI();
                $('#aspnetForm').append(msg.d);           
                $(selector).dialog({
                    width: width,
                    modal: true,
                    closeText: 'Close',
                    close: function(event, ui) {
                        $(selector).remove();
                    }
                });
                ApplyPadding();
            }
            else {
                $.unblockUI();
            }                 
        },
        error:
        function(xhr, textStatus, errorThrown) {
            alert(xhr.statusText);
            $.unblockUI();
        }
    });
}

function LogOff() {
    BlockUI();                        
    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        url: '/website/cms/CMSService.asmx/LogOff',
        success: function(msg) {
            if (msg.d) {
                window.location = '/';
            }
            else {
                alert('Could not log out!');
                $.unblockUI();
            }
        },
        error: function(xhr, textStatus, errorThrown) {
            alert(xhr.statusText);
            $.unblockUI();
        }
    });
}

function CorrectEmailaddress() {
    var txtEmail = $('#pf_Email');

    if ($(txtEmail).val().length > 255) {
        alert("Please enter at most 255 characters in the \"Email address\" field.");
        $(txtEmail).focus();
        return (false);
    }
    if ($(txtEmail).val() == "") {
        alert("Please enter a value for the \"Email address\" field.");
        $(txtEmail).focus();
        return (false);
    }
    if ($(txtEmail).val().length < 7) {
        alert("Please enter at least 7 characters in the \"Email address\"field.");
        $(txtEmail).focus();
        return (false);
    }
    pf_Email = $(txtEmail).val();
    at = pf_Email.indexOf("@");
    lastat = pf_Email.lastIndexOf("@");
    dot = pf_Email.lastIndexOf(".");
    if (at < 1 || at != lastat || dot < at) {
        alert("Your email address is not correct. Please try again.");
        $(txtEmail).focus();
        return false;
    }

    return true;
}

function ChangeLanguage(lcid, postbackUrl)
{
    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        url: '/website/cms/CMSService.asmx/ChangeLanguage',
        data: '{"lcid": "' + lcid + '"}',
        dataType: 'json',
        success: function(msg) {
            if (msg.d == 'OK')
                window.location = postbackUrl;
        },
        error: function(xhr, textStatus, errorThrown) {
            alert(xhr.statusText);
        }
    });
};

function LoadDealerCountries() {
    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        url: '/website/cms/CMSService.asmx/GetDealerCountries',
        dataType: 'json',
        success: function(msg) {
            if (msg.d != '-1') {
                var obj = eval(msg.d);
                $('#ddlCountries')
                    .find('option')
                    .remove()
                    .end()
                    .append('<option value="0">Country</option>')
                    .val('0')
                ;
                for (var i = 0; i < obj.length; i++) {
                    $('#ddlCountries').append('<option value="' + obj[i].ID + '">' + obj[i].Name + '</option>');
                }
            }
            else {
                alert('Could not load the specific dealer countries.');
            }
        },
        error: function(xhr, textStatus, errorThrown) {
            alert(xhr.statusText);
        }
    });
}

function LoadDealerRegions(countryCode) {
    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        url: '/website/cms/CMSService.asmx/GetDealerRegionsMaster',
        data: '{"countryCode": "' + countryCode + '"}',
        success: function(msg) {
            var obj = eval(msg.d);
            $('#ddlRegions')
                .find('option')
                .remove()
                .end()
                .append('<option value="0">All</option>')
                .val('0')
            ;
            for (var i = 0; i < obj.length; i++) {
                $('#ddlRegions').append('<option value="' + obj[i].ID + '">' + obj[i].Name + '</option>');
            }
        },
        error: function(xhr, textStatus, errorThrown) {
            alert(xhr.statusText);
        }
    });
}

function ChangeCountry(countrySelector, regionSelector, itemNo, variant) {
    BlockUI();
    var countryCode = $(countrySelector).val();
    //$('#country').val(countryCode);

    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: '{"countryCode": "' + countryCode + '", "itemNo": "' + itemNo + '", "variant": "' + variant + '"}',
        url: '/website/cms/CMSService.asmx/GetDealerRegions',
        dataType: 'json',
        success: function(msg) {
            var obj = eval(msg.d);
            $(regionSelector)
                .find('option')
                .remove()
                .end()
//                .append('<option value="0">All</option>')
//                .val('0')
            ;
            for (var i = 0; i < obj.length; i++) {
                $(regionSelector).append('<option value="' + obj[i].ID + '">' + obj[i].Name + '</option>');
            }
            $.unblockUI();
        },
        error: function(xhr, textStatus, errorThrown) {
            alert(xhr.statusText);
            $.unblockUI();
        }
    });
}

function ChangeRegion(cCode, rCode) {
    BlockUI();
    var countryCode = $('#ddlCountries').val();
    var regionCode = $('#ddlRegions').val();
    //var countryName = $("#ddlCountries option[value='" + countryCode + "']").text();
    //var regionName = $("#ddlRegions option[value='" + regionCode + "']").text();
    $('#region').val(regionCode);

    if (typeof (cCode) != 'undefined' && typeof (rCode) != 'undefined') {
        $('#country').val(cCode);
        $('#region').val(rCode);
    }

    $('form[name="DealersForm"]').submit();
}

function DoSearch(term) {
    var isOpen = $('#topSearchResult').parents('.ui-dialog:visible').length;
    
    if (!isOpen) {
        $('#topSearchResult').dialog({position: ['center',130], width: 904, height: 'auto'});
        $('#txtTopSearch').focus();
    }
    
    if (term.length <= 0) {
        $('#topSearchResult').dialog('close');
    }
    else {
        SearchProducts(term);
        SearchBlog(term);
        SearchPages(term);
    }
}

function SearchProducts(term) {
    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        url: '/website/cms/CMSService.asmx/ProductSearch',
        dataType: 'json',
        data: '{"term": "' + term + '", "count": "10"}',
        success: function(msg) {
            if (msg.d != '-1') {
                var result = eval('(' + msg.d + ')');
                var html = '';
                if (result.length > 0) {
                    $.each(result, function(key, it) {
                        html += '<div class="float-left" style="width:100%; margin-top:3px;"><a href="' + result[key].URL + '">' + result[key].Name + '</a></div>'; 
                    });
                }
                else {
                    html += '<div class="float-left">No products!</div>';
                }
                $('#pnlSearchResultProducts').html(html);
                $('div.pagingProducts').quickPager({pageSize:10, pagerID:1, selector:'pagingProducts'});
                //$('div.pagingProducts > div').highlight(term);
            }
            else {
                $('#pnlSearchResultProducts').html('No products!');
            }
        },
        error: function(xhr, textStatus, errorThrown) {
            $('#pnlSearchResultProducts').html('Error: ' + xhr.statusText);
        }
    });        
}

function SearchPages(term) {
    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        url: '/website/cms/CMSService.asmx/PageSearch',
        dataType: 'json',
        data: '{"term": "' + term + '", "count": "10"}',
        success: function(msg) {
            if (msg.d != '-1') {
                var result = eval('(' + msg.d + ')');
                var html = '';
                if (result.length > 0) {
                    $.each(result, function(key, it) {
                        html += '<div class="float-left" style="width:100%; margin-top:3px;"><a href="' + result[key].URL + '" target="_blank">' + result[key].Name + '</a></div>'; 
                    });
                }
                else {
                    html += '<div class="float-left">No pages!</div>';
                }
                $('#pnlSearchResultPages').html(html);
                $('div.pagingPages').quickPager({pageSize:5, pagerID:2, selector:'pagingPages'});
                //$('div.pagingBlog > div').highlight(term);
            }
            else {
                $('#pnlSearchResultPages').html('No pages!');
            }
        },
        error: function(xhr, textStatus, errorThrown) {
            $('#pnlSearchResultPages').html('Error: ' + xhr.statusText);
        }
    });        
}

function SearchBlog(term) {
    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        url: '/website/cms/CMSService.asmx/BlogSearch',
        dataType: 'json',
        data: '{"term": "' + term + '", "count": "10"}',
        success: function(msg) {
            if (msg.d != '-1') {
                var result = eval('(' + msg.d + ')');
                var html = '';
                if (result.length > 0) {
                    $.each(result, function(key, it) {
                        html += '<div class="float-left" style="width:100%; margin-top:3px;"><a href="' + result[key].Link + '" target="_blank">' + result[key].Title + '</a></div>'; 
                    });
                }
                else {
                    html += '<div class="float-left">No blog posts!</div>';
                }
                $('#pnlSearchResultArticles').html(html);
                $('div.pagingBlog').quickPager({pageSize:5, pagerID:3, selector:'pagingBlog'});
                //$('div.pagingBlog > div').highlight(term);
            }
            else {
                $('#pnlSearchResultArticles').html('No blog posts!');
            }
        },
        error: function(xhr, textStatus, errorThrown) {
            $('#pnlSearchResultArticles').html('Error: ' + xhr.statusText);
        }
    });        
}

function ApplyPadding() {
    /* Apply padding to page objects */
    var i = 0;
    $.each($('.pageArea > .pageobject'), function(key, value) {               
      $(value).removeClass('pad');
      if (i != 0) {
        $(value).addClass('pad');
      }
      
      var size = $(value).attr('size');
      if (size == typeof('undefined') || size == '')
        size = 1;
      else
        size = parseFloat(size);
      
      i += size;
      
      if (i >= 10)
        i = 0;
    });
}

$(document).ready(function() {
    LoadDealerCountries();

    $(".defaultText").focus(function(srcc) {
        if ($(this).val() == $(this)[0].title) {
            $(this).removeClass("defaultTextActive");
            $(this).val("");
        }
    });

    $(".defaultText").blur(function() {
        if ($(this).val() == "") {
            $(this).addClass("defaultTextActive");
            $(this).val($(this)[0].title);
        }
    });

    $(".defaultText").blur();

    $('#btnNewsletter').click(function() {
        if (CorrectEmailaddress()) {
            $('form[name="SubscriberForm"]').submit();
        }
    });
    
    ApplyPadding();
});
