function showHigherWrap(contents,coordX,coordY){
    var x = coordX;
    var y = coordY;
    
    $("#higher_wrap").html(contents);

    var child = $("#higher_wrap").children();
    
    setPosition(child[0],x,y);

    $("#higher_wrap").show();    
}

function hideHigherWrap(){
    $("#higher_wrap").empty();
    $("#higher_wrap").hide();
}

                                                      
function getBodyScrollTop(){
    return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
}                          
function getBodyScrollLeft(){
    return self.pageXOffset || (document.documentElement && document.documentElement.scrollLeft) || (document.body && document.body.scrollLeft);
}


function setPosition(element,coordX,coordY){
    var x = coordX;
    var y = coordY;

    element.style.position = 'relative';
    
    if (x == undefined || y == undefined){
        
        x = parseInt(document.body.clientWidth - $("#"+element.id).width())/2+getBodyScrollLeft();
        y = parseInt(document.body.clientHeight - $("#"+element.id).height())/2+getBodyScrollTop();

        
        if($.browser.msie && y < 320) y = 320;
    }
    
    element.style.left = x;
    element.style.top = y;                                                                              
}

function getPosition(elementId){                     
    element = document.getElementById(elementId);
        
    var left = 0;
    var top = 0;
    
    while (element){
        left   += element.offsetLeft;
        top    += element.offsetTop;
        element = element.offsetParent;
    }

    return {top:top,left:left};
}

function priceFormat(price){
    var price = price.toString();
    if (price.indexOf(".") == -1){
        price += '.00';
    }
    else{
        if (price.substring(price.indexOf(".")+1,price.length).length == 1 ){
            price += '0';
        }
    }
    return price;
}


function close(){
    hideHigherWrap();
}


function showMessage(text){

    var template = '';
    
    template += '<div id="system_message">';
    template += wrapBeginTemplate();
    template += '<b>'+text+'</b>';
    template += wrapEndTemplate();
    template += '</div>';
    
    showHigherWrap(template);

    /*if (!$.browser.msie){
        $("#higher_wrap").fadeTo(2440,0,function(){close();});
     }*/
//    else 
    setTimeout(close,1200);
}

/*
* ############################################## LOGIN ###################################
*/

function login(redirect, coordX, coordY){
    redirect_url = '/';          

    var x = coordX;
    var y = coordY;
    
    if (!$("#login_form").parent().is("#higher_wrap")){                            
        
        if (x == undefined || y == undefined){
            x = $("body").width()-285;
            if($.browser.msie) x = x -20;
            y = 160;
        }
        
        showHigherWrap('<div id="login_form">'+loginTemplate()+'</div>',x,y);
    }
    
}
    
function loginValidate(){
    email       = document.getElementById("login_email");
    var password    = document.getElementById("password");
    var emailRegexp = /^([a-z0-9_-]+[\.]?)*[a-z0-9_-]+@([a-z0-9_-]+[\.]?)*([a-z0-9_-]+)\.[a-z0-9]+$/i;
    
    var error = 0;
   
    if( email.value == '' ){
        error = 1;
    }
    else if( !emailRegexp.test(email.value) ){
        error = 2;
    }
    
    if( error == 0 && password.value == '' ){
        error = 3;
    }
           
    if( error != 0 ){
        switch(error){
            case 1: alert('Введите e-mail который вы использовали при регистрации!');
                break;
            case 2: alert('Не правильный формат e-mail адреса!');
                break;
            case 3: alert('Введите пароль!');
                break;
        }   
    }           
    else{
        loginLoader(); 
        $.post(
                    '/utils/login.php',
                    {
                        email:email.value,
                        password:password.value
                     }
                     ,
                     loginConfirmation
                );
    }
    
    return false;
      
}

function loginConfirmation(data){
    
    if(data.length > 0){
       eval(data);
       
       if( user_login  == true ){
           //showMessage(user_name); 
//           showMessage('Добро пожаловать, '+user_name+'!'); 
           var login_link_content = '<h2>Добро пожаловать!</h2><strong>Пользователь:</strong> '+user_name+'<a href="/logout/" id="logout">Выйти</a>';

           $("#login").html(login_link_content);
         
           if (redirect_url = '/'){
                location.href = '';
           }
       }
       else{
           errorMessage = '';
           for( i=0; i<errors.length; i++){
                errorMessage += errors[i]+'\n';
           } 
           alert(errorMessage);
           loginFailed();
       } 
    }
}

function loginLoader(){                   
    $("#close").hide();
    $("#login_loader").show();
    $("#enter").attr("disabled","disabled");
}
function loginFailed(){  
    $("#login_loader").hide(); 
    $("#close").show();                    
    $("#enter").attr("disabled","");
}




/*
* ####################################### G A L L E R Y  #################################################################
*/

function addToGallery(id,imageTitle,imageWidth,imageHeight,index){

     $("#product_gallery_images").append('<div id="product_gallery_item'+index+'"></div>');
     
     if (index==1){
        $("#product_gallery_item1").append(loaderTemplate());
        $("#login_loader").show();
     }
     if (index==2){
         $("#gallery_navigation").html(navGalleryTemplate(1)+navGalleryTemplate(2));
     }
     else if(index>2){
        $("#gallery_navigation").append(navGalleryTemplate(index));
     }
     $.get(
                '/image.php',
                {
                    name:imageTitle,
                    parentID:id,
                    width:imageWidth,
                    index:index,
                    height:imageHeight,
    //                fragment:'yes',
                    dirname:'products',
                    info_only:'yes'
                 },
                 buildingGallery
            ); 
}

function buildingGallery(data){
    
    if (data.length>0){
        eval(data);       
        
        if (index==1){
            $("#product_gallery").width(imageWidth);
            $("#product_gallery_item"+index).empty();
        }
        
        $("#product_gallery_images").width($("#product_gallery_images").width()+imageWidth);
        
        if (imageHeight > $("#product_gallery_images").height() ) $("#product_gallery_images").height(imageHeight); 
                
        $("#product_gallery_item"+index).css({
                                            width:imageWidth,
                                            height:'100%', 
                                            background:"url("+imageUrl+") no-repeat center"
                                           });
        setPosition(document.getElementById("product"));
    }
}
    

function galleryItem(id){
    var width = 0;
    
    for(i=1;i<id;i++){
       width += $("#product_gallery_item"+i).width();
    }                                                                                                     
    
    $("#product_gallery").width($("#product_gallery_item"+id).width());
    $("#product_gallery_images").css("margin-left",-width);
}



/*
*  ####################### Templates #####################################
*/

 
function loginTemplate(){

    var loginTemplate = '';
    
    loginTemplate += wrapBeginTemplate();
    
    loginTemplate += '<form action="" method="post" onSubmit="return loginValidate();">';
    loginTemplate += '<table border="0" cellpadding="3" cellspacing="0" width="225">';                             
    loginTemplate += '<tr><td colspan="2" align="right"><div id="higher_top"><a href="javascript:close();" title="Закрыть" id="close">Закрыть</a>'+loaderTemplate()+'</div></td></tr>';
    loginTemplate += '<tr><td width="50"><span class="pink_ed"><strong>E-mail:</strong></span></td><td width="175"><input type="text" name="email" id="login_email" value=""></td></tr>';
    loginTemplate += '<tr><td><span class="pink_ed"><strong>Пароль:</strong></span></td><td><input type="text" name="password" id="password" value=""></td></tr>';
    loginTemplate += '<tr><td colspan="2" valign="bottom"><table border="0" cellspacing="0" cellpadding="0"><tr><td valign="bottom" class="link_min" align="left"><a href="/forgot-password/">Забыли пароль?</a><br /><a href="/registration/">Зарегистрироваться</a></td><td valign="bottom" align="right" width="150"><input name="submit" type="submit"  id="enter" value="Войти" onfocus="this.blur();" class="submit"></td></tr></table></td></tr>';
    loginTemplate += '</table>'; 
    loginTemplate += '</form>';
    
    loginTemplate += wrapEndTemplate();
    
    return loginTemplate;
}

function loaderTemplate(){
    return '<img src="/images/login-loader.gif" width="16" height="16" id="login_loader" style="display:none;">';
}

function closeTemplate(){
    return '<a href="javascript:close();" title="Закрыть" id="close">Закрыть</a>';
}

function navGalleryTemplate(id){
    return '<a href="javascript:galleryItem('+id+');">'+id+'</a>&nbsp;&nbsp;&nbsp;';
}  


function wrapBeginTemplate(){
    var template  = '<table border="0" cellpadding="0" cellspacing="0" class="box">';
    template     += '<tr><td height="10"></td><td width="15" height="5" class="box_top"></td></tr>';
    template     += '<tr><td class="box_content">';
    return template;
}  

function wrapEndTemplate(){
    var template = '</td><td class="box_right">&nbsp;</td></tr>';
    template    += '<tr><td height="5" class="box_bottom"></td><td class="box_bottom_right"></td></tr>';
    template    += '</table>';
    return template;
}  