jQuery(document).ready(function(){
    // Функции удаления пробелов в начале и конце строки
    function trim(s) { return rtrim(ltrim(s)); }
    function ltrim(s) { return (typeof s == 'string' && s.length) ? s.replace(/^\s+/, '') : ''; }
    function rtrim(s) { return (typeof s == 'string' && s.length) ? s.replace(/\s+$/, '') : ''; }
    
    // Доменное имя для перехода
    function domainName(sName, sDomain)  {
        var newName = "";				
        
        var testServ = trim(document.URL).indexOf("test.webprofy.com");
        if (testServ != -1) { sDomain = "gazony.test.webprofy.com"; }

        if (sDomain.indexOf("www.") == 0) {
            sDomain = sDomain.replace("www.", "");
        }

        if(sName) {
            newName = sName + "." + sDomain;
        } else {
            newName = sDomain;
        }
        
        return trim(newName);
    }

    // Новый URL страницы
    function changeUrl(newDomain) {
        var re = new RegExp("http:\/\/[A-Za-z0-9.]+","g");
        var newUrl;
        
        if(newDomain) {
            newUrl = document.URL.replace(re, "http://www."+newDomain);
        } else {
            newUrl = document.URL.replace(re, "http://www.");
        }
		
		return trim(newUrl);
    }

    // Установка текущего URL в SELECT
    jQuery("#default-usage-select option:gt(0)").each(function(){
        var loc = trim(document.URL).indexOf(domainName(trim(this.value), trim(this.name)));
        if (loc != -1) { 
            jQuery(this).attr("selected", "selected"); 
            jQuery("span.jquery-selectbox-currentItem").text(this.innerHTML);
        }
    });

    // Событие на изменение URL в SELECT
    jQuery("#default-usage-select").change(function(){
        var sNewName = domainName(jQuery("#default-usage-select option:selected").attr("value"), jQuery("#default-usage-select option:selected").attr("name"));
        
        // Для MSIE - хитрая подмена URL
        if (jQuery.browser.msie) {
            // Получаем текущий город, а по нему - URL из SELECT
            var __curCity = trim(jQuery("span.jquery-selectbox-currentItem").text());
            jQuery("#default-usage-select option").each(function() {
                if (__curCity == trim(this.innerHTML)) {
                    document.location = changeUrl(domainName(trim(this.value), trim(this.name)));
                }
            });
        } else { // Для остальных оставляем функционал без изменения
            document.location = changeUrl(sNewName);
            jQuery("#default-usage-select option:gt(0)").each(function(){
                var loc = trim(document.URL).indexOf(trim(jQuery(this).attr("value")));
                if(loc != -1) { jQuery(this).attr("selected", "selected"); }
            });
        }
    });
    
});
