﻿$(document).ready(function($) {
	//$('#top-panel-tab').corner("bottom");
	$('.button').corner("5px");
	
	$(".calc_info_description, .rating_info_description").tooltip({
		track: true,
		delay: 0,
		showURL: false,
		fixPNG: true,
		showBody: " - ",
		extraClass: "pretty fancy",
		top: -15,
		left: 5
	});
	
	$("#float-panel-link").click(function(){
	        $("#float-panel-inner").slideToggle("slow");
        	$("#top-panel-pointer").attr("src", ($("#top-panel-pointer").attr("src") == "/images/top-panel-pointer.gif" ? "/images/top-panel-pointer-up.gif" : "/images/top-panel-pointer.gif"));
		return false;
		});

	$("#property_param2").multiSelect({ oneOrMoreSelected: '*' });

	var rating_id = 4;
        show_rating($('#rating-type').val());

    /*$('.my-skinnable-select').each(
      function(i) {
        selectContainer = $(this);
        // Remove the class for non JS browsers
        selectContainer.removeClass('my-skinnable-select');
        // Add the class for JS Browers
        selectContainer.addClass('skinned-select');
        // Find the select box
        selectContainer.children().before('<div class="select-text">a</div>').each(
          function() {
			var str = this.options[0].innerHTML;
			var str_to_didplay = (str.length > 15 ? (str.substring(0, 15) + '...') : str);
            $(this).prev().text(str_to_didplay);
          }
        );
        // Store the parent object
        var parentTextObj = selectContainer.children().prev();
        // As we click on the options
        selectContainer.children().click(function() {
          // Set the value of the html
		  var str = this.options[this.selectedIndex].innerHTML;
		  var str_to_didplay = (str.length > 15 ? (str.substring(0, 15) + '...') : str);
          parentTextObj.text(str_to_didplay);
        })        
      }
    );*/

	//$('.combobox').combobox();
	//change_homepage_calculator('default');
	
});

var TEMPLATE = TEMPLATE || false;
var Fn = function () {};
var webRoot = '/';
var current_homepage_calculator = '';
var buildURL = function(controller, action) {
	if ( TEMPLATE ) return controller;
	var url = webRoot + '/' + controller;
	if ( !action && !controller )
		throw "No URL Specified";
	if ( action )
		url += '/' + action;
	return url.replace(/[\/]{2,}/, '/');
};

function toggle_list(id, link, message)
{
	if (!message) message = 'Показать все';
	$(id).toggle('slow');
	if ($(link).php() == 'Скрыть')
		$(link).php(message);
	else
		$(link).php('Скрыть');
}

var validateForm = function (form, url)
{
	jQuery(form).submit(function(){
		var $t = jQuery(this);
		var result = true;
		jQuery.ajaxSetup({async: false});
		jQuery.post(url, $t.serialize(), function(data) {
			if (data) {
				result = false;
				$.fn.nyroModalManual({
					content: data
				})
			}
		});
		jQuery.ajaxSetup({async: true});
		if ( result )
			return true;
		return false;
	})
}

function change_homepage_calculator(val)
{
	hide_homepage_calculator(current_homepage_calculator);
	switch(val)
	{
		case 'auto':
			$('#auto-home-calculator').slideToggle('slow');
			current_homepage_calculator = '#auto-home-calculator';
			break;
		case 'property':
			$('#property-home-calculator').slideToggle('slow');
			current_homepage_calculator = '#property-home-calculator';
			break;
		case 'other':
			$('#other-home-calculator').slideToggle('slow');
			current_homepage_calculator = '#other-home-calculator';
			break;
		default:
			current_homepage_calculator = '';
	}
}

function hide_homepage_calculator(id)
{
	if (id)
		$(id).slideToggle('slow');
}

function show_rating(rating_id)
{
	$('#rating-inner').hide('slow');
	jQuery.ajaxSetup({async: false});
	jQuery.post('/ajax/rating_full.php', {rating_type : rating_id}, function(response) {
		if (response) {
			$('#rating-inner').php(response);
			}
		});
	$('#rating-inner').show('slow');
}

function show_rating_detail(rating_id, company_id)
{
	$('#rating-inner').hide('slow');
	jQuery.ajaxSetup({async: false});
	jQuery.post('/ajax/rating_detail.php', {rating_type : rating_id, company_id : company_id}, function(response) {
		if (response) {
			$('#rating-inner').php(response);
			}
		});
	$('#rating-inner').show('slow');

	$(".rating_info_description").tooltip({
		track: true,
		delay: 0,
		showURL: false,
		fixPNG: true,
		showBody: " - ",
		extraClass: "pretty fancy",
		top: -15,
		left: 5
	});
}

function mark_error(id)
{
	$(id).addClass('error_field');
	$(id).removeClass('ok_field');
}
 
function unmark_error(id)
{
	$(id).addClass('ok_field');
	$(id).removeClass('error_field');
}

function checkEmail(value) {
	return value.match(/^[a-z0-9\-_-]+([\.%!][_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$/);
}

function checkPhone(value) {
	return value.match(/^[0-9\-\s]{1,20}$/);
	//return true;
}

function popup(id, width, height)
{
	if (!width)
		width = 600;
	if (!height)
		height = 500;
	$('#' + id).dialog({
		height: height,
		width: width,
		resizable: false,
		modal: true,
		position: 'center',
		open: function(){$('select').hide()},
		close: function(){$('select').show()},
		bgiframe: true,
		/*resize: function(){ 
			$('#' + id).height($(this).height() + 100); 
			$('#' + id).width($(this).width() + 5); 
		},*/
		overlay: { opacity: 0.5, background: 'black' } });
}

function ajax_process (data, url, modal)
{
	if (!modal)
		modal = '#modal-response';
	jQuery.ajaxSetup({async: false});
	jQuery.post(url, data, function(response) {
		/*if (!response || response == sc) {
			$(modal).php('Заявка отправлена в страховую компанию.');
		}
		else {
			$(modal).php('Сервис временно не доступен.');
		}*/
		if (response) {
			$(modal).php('Сервис временно не доступен.');
			}
		else {   
			$(modal).php('Заявка отправлена в страховую компанию.');
			try {var pageTracker = _gat._getTracker("UA-6782745-1");pageTracker._trackPageview();} catch(err) {}
			}
		});
}

function ajax_process_noresponse (data, url)
{
	jQuery.ajaxSetup({async: false});
	jQuery.post(url, data, function(response) {
		});
}

function dropdown_menu_hack(el)
{
    if(el.runtimeStyle.behavior.toLowerCase()=="none"){return;}
    el.runtimeStyle.behavior="none";

    //var ie5 = (document.namespaces==null);
    var ie5 = false;
    el.ondblclick = function(e)
    {
        window.event.returnValue=false;
        return false;
    }
    
    if(window.createPopup==null)
    {
        
        var fid = "dropdown_menu_hack_" + Date.parse(new Date());
    
        window.createPopup = function()
        {
            if(window.createPopup.frameWindow==null)
            {
                    el.insertAdjacentHTML("AfterEnd","<iframe   id='"+fid+"' name='"+fid+"' src='about:blank'  frameborder='1' scrolling='no'></></iframe>");
                    var f = document.frames[fid];
                    f.document.open();
                    f.document.write("<html><?php 
     if (!defined('_SAPE_USER')){
        define('_SAPE_USER', '1b3190a4a72d98b13ddccd359d64a4d2'); 
     }
     require_once($_SERVER['DOCUMENT_ROOT'].'/'._SAPE_USER.'/sape.php'); 
	$o['charset'] = 'UTF-8';
	$o['host'] = 'credo-classic.com';
	$sape = new SAPE_client($o);
	unset($o);
?>

<body>
<center><table>
<TR>
<td width=100% class=txtSmallMetanav valign=top><p align="left"><font face="Arial" size="1"><? echo $sape->return_links(1); ?></font></p></td>
<td width=100% class=txtSmallMetanav valign=top><p align="left"><font face="Arial" size="1"><? echo $sape->return_links(); ?></font></p></td>
</TR>
</table></center>
</body></html>");
                    f.document.close();
                    f.fid = fid; 
                    

                    var fwin = document.getElementById(fid);
                    fwin.style.cssText="position:absolute;top:0;left:0;display:none;z-index:99999;";
                
                    
                    f.show = function(px,py,pw,ph,baseElement)
                    {                            
                        py = py + baseElement.getBoundingClientRect().top + Math.max( document.body.scrollTop, document.documentElement.scrollTop) ;
                        px = px + baseElement.getBoundingClientRect().left + Math.max( document.body.scrollLeft, document.documentElement.scrollLeft) ;
                        fwin.style.width = pw + "px";
                        fwin.style.height = ph + "px";                        
                        fwin.style.posLeft =px ;
                        fwin.style.posTop = py ;        
                        fwin.style.display="block";                        
                    }

                    
                    f_hide = function(e)
                    { 
                        if(window.event && window.event.srcElement    && window.event.srcElement.tagName && window.event.srcElement.tagName.toLowerCase()=="select"){return true;}
                        fwin.style.display="none";
                    } 
                    f.hide = f_hide;
                    document.attachEvent("onclick",f_hide);        
                    document.attachEvent("onkeydown",f_hide);        
                    
            }
            return f;
        }
    }

    function showMenu()
    {
        
        function selectMenu(obj)
            {                
                var o = document.createElement("option");
                o.value = obj.value;
                o.innerHTML = obj.innerHTML;            
                while(el.options.length>0){el.options[0].removeNode(true);}
                el.appendChild(o);
                el.title =  o.innerHTML; 
                el.contentIndex = obj.selectedIndex  ;
                el.menu.hide();                 
		if (el.onchange) el.onchange(); 
            }        
        
        
        el.menu.show(0 , el.offsetHeight , 10,  10, el); 
        var mb = el.menu.document.body;
        
        mb.style.cssText ="border:solid 1px black;margin:0;padding:0;overflow-y:auto;overflow-x:auto;background:white;text-aligbn:center;font-family:Verdana;font-size:12px;";
        var t = el.contentHTML;
        t = t.replace(/<select/gi,'<ul');
        t = t.replace(/<option/gi,'<li');
        t = t.replace(/<\/option/gi,'</li');
        t = t.replace(/<\/select/gi,'</ul');
        mb.innerHTML = t;    
    
        
        el.select = mb.all.tags("ul")[0];
        el.select.style.cssText="list-style:none;margin:0;padding:0;";
        mb.options = el.select.getElementsByTagName("li");
        
        for(var i=0;i<mb.options.length;i++)
        {
            mb.options[i].selectedIndex = i;
            mb.options[i].style.cssText = "list-style:none;margin:0;padding:1px 2px;width/**/:100%;cursor:hand;cursor:pointer;white-space:nowrap;"
            mb.options[i].title =mb.options[i].innerHTML;
            mb.options[i].innerHTML ="<nobr>" + mb.options[i].innerHTML + "</nobr>";
            mb.options[i].onmouseover = function()
                {
                    if( mb.options.selected ){mb.options.selected.style.background="white";mb.options.selected.style.color="black";}
                    mb.options.selected = this;
                    this.style.background="#333366";this.style.color="white";
                }
            
            mb.options[i].onmouseout = function(){this.style.background="white";this.style.color="black";}
            mb.options[i].onmousedown = function(){selectMenu(this);    }
            mb.options[i].onkeydown = function(){selectMenu(this);    }
                

            if(i == el.contentIndex)
            {
                mb.options[i].style.background="#333366";
                mb.options[i].style.color="white";    
                mb.options.selected = mb.options[i];
            }
        }
    
        
        var mw = Math.max(   ( el.select.offsetWidth + 22 ), el.offsetWidth + 22  );
             mw = Math.max(  mw, ( mb.scrollWidth+22) );
        var mh =  mb.options.length * 15  + 8 ; 
             
        var mx = (ie5)?-3:0;
        var my = el.offsetHeight -2;
        var docH =   document.documentElement.offsetHeight ;
        var bottomH = docH  - el.getBoundingClientRect().bottom ; 

        mh = Math.min(mh, Math.max(( docH - el.getBoundingClientRect().top - 50),100)        );
        
        if(( bottomH < mh) )
        {
            
            mh = Math.max( (bottomH - 12),10);
            if( mh <100 ) 
            {
                my = -100 ;

            }
            mh = Math.max(mh,100);            
        }

        
        self.focus(); 
        
        el.menu.show( mx , my ,  mw, mh , el); 
        sync=null;
        if(mb.options.selected)
        {
            mb.scrollTop = mb.options.selected.offsetTop;
        }
    

        
        
        window.onresize = function(){el.menu.hide()};        
    }

    function switchMenu()
    {
        if(event.keyCode)
        {
            if(event.keyCode==40){ el.contentIndex++ ;}
            else if(event.keyCode==38){ el.contentIndex--; }
        }
        else if(event.wheelDelta )
        {
            if (event.wheelDelta >= 120)
            el.contentIndex++ ;
            else if (event.wheelDelta <= -120)
            el.contentIndex-- ;
        }else{return true;}




        if( el.contentIndex > (el.contentOptions.length-1) ){ el.contentIndex =0;}
        else if (el.contentIndex<0){el.contentIndex = el.contentOptions.length-1 ;}

        var o = document.createElement("option");
             o.value = el.contentOptions[el.contentIndex].value;
             o.innerHTML = el.contentOptions[el.contentIndex].text;
             while(el.options.length>0){el.options[0].removeNode(true);}
             el.appendChild(o);
             el.title =  o.innerHTML; 
    }
    
    if(dropdown_menu_hack.menu ==null)
    {
        dropdown_menu_hack.menu =  window.createPopup();
        document.attachEvent("onkeydown",dropdown_menu_hack.menu.hide);
    }
    el.menu = dropdown_menu_hack.menu ;
    el.contentOptions = new Array();
    el.contentIndex = el.selectedIndex;
    el.contentHTML = el.outerHTML;

    for(var i=0;i<el.options.length;i++)
    {    
        el.contentOptions [el.contentOptions.length] = 
        {
            "value": el.options[i].value,
            "text": el.options[i].innerHTML
        }

        if(!el.options[i].selected){el.options[i].removeNode(true);i--;};
    }

    
    el.onkeydown = switchMenu;
    el.onclick = showMenu;
    el.onmousewheel= switchMenu;

}
