$(document).ready(function() {
    $("#b_button").bind("click", function()
        {    
            $.get("/proj/trevireceipts/html__/contact.html?"+Math.random(),
                function (data)
                {
                    $("#info").html(data);
                    $("#content").jScrollPane({maintainPosition: false});
                }
            );
        }
    );
    $("#btnhs").bind("click", Main.toggleBody);
    $("#counters img").animate({opacity:.4}, 20);
    
    /*var this_url = document.location.href;
    if (this_url.indexOf('#recipe') != -1) {
        var myRe = /recipe(\d)/ig;
        var myArray = myRe.exec(this_url);
        //alert(myArray[1]);
    }*/
    
});


function historyCall(hash, sl) 
{
    
    if(hash) 
    {
        if (!sl) 
        {
            if (hash == 'fc')
            {
                hash = $.cookie('last_url');
            }

            issue    = Main.historyPull[hash]['issue'];

            if (issue == 'loadReceipts_')
            {
                title        = Main.historyPull[hash]['title'];
                id            = Main.historyPull[hash]['id'];
                href        = Main.historyPull[hash]['href'];
                Main.loadReceipts_(title, id, href, 1);
            }
            else if (issue == 'loadReceipt')
            {
                id            = Main.historyPull[hash]['id'];
                url        = Main.historyPull[hash]['url'];
                Main.loadReceipt(id, url, 1);
            }
            else if (issue == 'go_')
            {
                id            = Main.historyPull[hash]['id'];
                Main.go_(id, 1);
            }
        }
    } else 
    {
        window.location.href = '/';
    }

}


var noTrack = 0;

var Main = {
    imgCntFromMenuLoaded:0,
    imgFromMenu : [],

    historyPull : {},

    preInit : function()
    {

        // Set recipe bg
        /*$('#plaha').createAppend(
            'div', {className:"plaha-bg"}
        ).css({opacity: 0.7}).createAppend(
            'div', {className:"plaha-bg-border"}
        );*/
        
        $('#plaha').append('<div class="plaha-bg" style="opacity: 0.7"> <div class="plaha-bg-border"></div> </div>');
        
        setTimeout("Interface.playCookies()", 1000);
        
        for(var i=1;i<6;i++)
        {
            Main.imgFromMenu.push(_img +"cookie"+i+".gif");
            /*
            if($.browser.msie)
            {
                var img = new Image();
                /*
                img.onload = function()
                {
                    Main.imgMenuAdd();
                }
                */
                /*
                var src = _img + "cookie"+i+".gif";
                Main.imgFromMenu[Main.imgFromMenu.length] =  src;
                img.src = src;

                if(i==5)
                    setTimeout("Interface.playCookies()", 10000);                    
                
            }
            else
            {
                var img = new Image();
                img.onload = function()
                {
                    Main.imgMenuAdd();
                }
                Main.imgFromMenu[Main.imgFromMenu.length] = img.src= _img + "cookie"+i+".gif";
            }*/
        }
        
        $.fn.media.defaults.bgColor="";
        $('#plate').media({
            width:     293,
            height:    286,
            src:       "/proj/trevireceipts/i/swf/tlogo.swf",
            attrs:     {id:"swf_logo", wmode: 'transparent', scale: "noborder", quality:"high"},  // object/embed attrs 
            params:    {id:"swf_logo", wmode: 'transparent', scale: "noborder", quality:"high"} // object params/embed attrs 
        });
        Main.init();

    },

    imgMenuAdd : function()
    {
        Main.imgCntFromMenuLoaded++;
        if(Main.imgCntFromMenuLoaded==5)
        {
            Interface.playCookies();
        }
    },

    init: function()
    {
        for(var i=1;i<6;i++)
        {
            /*$("#cookie"+i).createAppend(
                'img', {width:143, height:96, src:Main.imgFromMenu[i-1], id:"#cookie"+i}
                );*/
            
            $("#cookie"+i).append('<img id="#cookie' + i + '" height="96" width="143" src="' + Main.imgFromMenu[i-1] + '" alt="" />');
                //'img', {width:143, height:96, src:Main.imgFromMenu[i-1], id:"#cookie"+i}
                //);
                
                
        }
        if($.browser.mozilla)
            $("#plaha").animate({opacity:.9}, 100);
        $("#receipts").jScrollPane({maintainPosition: false});
        $(".randomRecipe").bind("click", function(){Main.loadReceipt(this.id.replace("rndr", ""), this);});
        Interface.highlightItems();
        $.fn.media.defaults.bgColor="";
        /*
        $('#snd2').media({
            width:     115,
            height:    25,
            src:       "/proj/trevireceipts/i/swf/sound.swf",
            attrs:     {id:"swf_sound", wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"sameDomain"},  // object/embed attrs 
            params:    {id:"swf_sound", wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"sameDomain"} // object params/embed attrs 
        });
        */
        setTimeout(function()        // 15000
        {
            $(".counters").css({display:"block"});
            var rnd =Math.floor(Math.random()*2);
            var clickTAG ="";
            switch(rnd)
            {
                case 0:
                    clickTAG = "http://www.trevicarriages.com/";
                    break;
                case 1:
                    clickTAG = "http://www.liptont.com/";
                    break;
            }
            $('#a66c3901').media({
                width:     200,
                height:    200,
                src:       "/proj/trevireceipts/i/swf/src"+rnd+".swf?clickTAG="+clickTAG,
                attrs:     {id:"swf_sound",  quality:"high", allowscriptaccess:"sameDomain"},  // object/embed attrs 
                params:    {id:"swf_sound",  quality:"high", allowscriptaccess:"sameDomain"} // object params/embed attrs 
            });
            switch(rnd)
            {
                case 0:
                    clickTAG = "http://ballarini.com";
                    break;
                case 1:
                    clickTAG = "http://www.bandbliqueur.com";
                    break;
            }
            $('#top100').media({
                width:     "100%",
                height:    60,
                src:       "/proj/trevireceipts/i/swf/top"+rnd+".swf?clickTAG="+clickTAG,
                attrs:     {id:"swf_sound",  quality:"high", allowscriptaccess:"sameDomain"},  // object/embed attrs 
                params:    {id:"swf_sound",  quality:"high", allowscriptaccess:"sameDomain"} // object params/embed attrs 
            });
        }, 10000);
        if(document.location.host.indexOf(".klik")==-1)
            setTimeout("loadSound();", 20000);
        Data.load();
        
        $("#content").jScrollPane({maintainPosition: false});
        jQuery.each($("#cookies .cookie"), function()
            {
                /*$(this).createAppend(
                    'div', {className:"eff"}
                    );*/
                $(this).append('<div class="eff"></div>');
                
                $(this).append('<div class="layer"></div>');
                
                $(this).find('.layer').mouseover(function() { // событие, когда указатель мыши проходит над объектом или областью.
                    var elem_parent = $(this).parent();
                    var vilka_elem = $('.vilka', elem_parent);
                    vilka_elem.stop();
                    try {
                        document.getElementById("swf_sound").videlec();    
                    } catch (e) {
                        //--
                    }
                    
                    vilka_elem.animate({top:-160}, 200, function(){ // step_1
                        vilka_elem.animate({top:-180}, 100, function(){ // step_2
                            vilka_elem.animate({top:-160}, 50); // step_3
                        }); // step_2 end
                    }); // step_1 end
                    
                }).mouseout(function(){ ///событие, когда указатель мыши покидает определенную область.
                    var elem_parent = $(this).parent();
                    var vilka_elem = $('.vilka', elem_parent);
                    vilka_elem.stop().animate({top:-290}, 600);
                }).click(function(){
                    Main.go_($("a", $(this).parent()).attr("id"));    
                });
                
                  
                /*$(this).createAppend(
                    'div', {className:"layer",onmouseover:function()
                        {
                            $(".vilka", $(this).parent()).stop();
                            try
                            {
                                document.getElementById("swf_sound").videlec();
                            }
                            catch (e)
                            {
                            }
                            
                            $(".vilka", $(this).parent()).animate({top:-160}, 200, function()
                                {    
                                    $(".vilka", $(this).parent()).animate({top:-180}, 100, function()
                                        {
                                            $(".vilka", $(this).parent()).animate({top:-160}, 50);
                                        }
                                    );
                                }
                            );
                        },
                        onmouseout : function()
                        {
                            $(".vilka", $(this).parent()).stop();
                            $(".vilka", $(this).parent()).animate({top:-290}, 600);
                        },

                        onclick : function()
                        {
                            Main.go_($("a", $(this).parent()).attr("id"));
                        }
                    }
                );*/ // createAppend end
            }
        );
    },

    navigate : function(url)
    {

    },

    go_ : function(id, h)
    {
        // History Add
        if (!h)
        {
            key = 'page:' + id ;
            Main.historyPull[key] = {'issue':'go_', 'id':id};
            $.historyLoad(key, true);
        }
        // --

        var a = id;
        if(a == "/")
            a = "index.html";
        if(/^http/.test(a))
            document.location = a;

        if ($('#i-data').length)
        {
            var data = $('u[a="'+a+'"]', $('#i-data')).html();
            $("#info").html(data);
            $("#content").jScrollPane({maintainPosition: false});
        }
        else
        {
            $.get("/proj/trevireceipts/html__/"+a+"?"+Math.random(),
                function (data)
                {
                    $("#info").html(data);
                    $("#content").jScrollPane({maintainPosition: false});
                }
            );
        }
    },

    loadData : function(url, func)
    {
        $.get(url,
            function (data)
            {
                Data.data = data;
                func();
            }
        );
    },

    loadReceipts : function(obj)
    {
        
        $("#left ul").css({opacity:1});
        var cid        = $(obj).attr("id").replace('.html', '').replace('c', '');
        var html    = obj.innerHTML;
        var id        = obj.id;
        var href    = $(obj).attr("href");

        $('#receipt-cat-title').html(html);
        
        $('#receipts').animate({opacity: .2}, 500, function() {
                Main.loadData("/proj/trevireceipts/html__/data.php?cid=" + cid, function () {
                        Main.loadReceipts_(html, id, href, false);
                        $('#receipts').animate({opacity: 1}, 800);
                    });
            });

        return false;
    },

    loadReceipts_ : function(title, id, href, h)
    {

        if (!h)
        {
            key = href.replace('/recipes/', '').replace('.html', '').replace('/', ':');
            Main.historyPull[key] = {'issue':'loadReceipts_', 'title':title, 'id':id, 'href':href};
            $.historyLoad(key, true);
        }
        else
        {
            $('#receipts').animate({opacity: 0.2}, 500, function() {

                    var cid = id.match(/c([^.]+)\.html/);
                    cid = cid[1];

                    Main.loadData("/proj/trevireceipts/html__/data.php?cid=" + cid, function () {
                            Main.loadReceipts_(title, id, href, false);
                            $('#receipts').animate({opacity: 1}, 800);
                        });
                });

            return false;
        }

        // --
        document.title = 'TreviGourmet :: ' + title;

        $('#cat-title').html(title);
        var items = Data.loadItems(id);

        if (!$('#i-data').length && !noTrack)
        {
            if(typeof(pageTracker) == "object")
            {
                pageTracker._trackPageview(href);
            }
        }


        $("#receipts").html("");
        /// ssssss
        for (i=0;i<items.length;i++)
        {
            // /recipes/8/meat/301/baked-pork-with-mushrooms.html           
            var a_href_id = $(items[i]).attr("id");
            var tmp_html  = '<div class="item">';
                tmp_html += '   <div class="img">';
                tmp_html += '       <a id="' + a_href_id + '" href="#">';
                tmp_html += '           <img src="' + _img + 'photos/icon/'+$(items[i]).attr("id")+'.jpg' + '" width="85" height="86" alt="img" />';
                tmp_html += '       </a>';
                tmp_html += '   </div>';
                tmp_html += '   <div>' + $(items[i]).attr("name") + '</div>';
                tmp_html += '</div>'
            
            $('#receipts').append(tmp_html); 
            $('#receipts').find('#' + a_href_id).click(function(){
                
                Main.loadReceipt(id, $(items[i]).attr("id"));
                return false;    
            });
            
            /*$("#receipts").createAppend(
                'div', {className:'item'}, [
                    'div', {className:'img'}, [
                        'a', {id:$(items[i]).attr("id"), href:'#', onclick: function()
                            {

                                Main.loadReceipt(id, $(items[i]).attr("id"));
                                return false;
                            }
                        }, [
                            'img', {src:_img + 'photos/icon/'+$(items[i]).attr("id")+'.jpg',width:'85',height:'86'}
                        ]
                    ],
                    'div', {}, $(items[i]).attr("name")
                ]
            );   */
        }

        $("#receipts").jScrollPane({maintainPosition: false});
        Interface.highlightItems();
        return false;
    },

    loadReceipt : function(id, url, h)
    {
        if (!h)
        {
            key =  'recipe' + id; // url.replace('/recipes/', '').replace('.html', '').replace(/\//gi, ':');
            Main.historyPull[key] = {'issue':'loadReceipt', 'id':id, 'url':url};
            $.historyLoad(key, true);
        }
        ///document.location.href = 'http://www.trevigourmet.com/#' + key + ':' + url;
        try
        {
            document.getElementById("swf_sound").plate();
        }
        catch (e)
        {

        }
        var d = Data.loadItem(id);
        if($(d).length==0)
            return false;
        var _nm = $(d).attr("name");
        var _n = $(d).attr("name").toLowerCase().replace(/\&/gi, 'and').replace(/ /gi, '-');
        var _nid = $(d).attr("id");
        var _c = $(d).parent().attr("name").toLowerCase().replace(/\&/gi, 'and').replace(/ /gi, '-');
        var _cid = $(d).parent().attr("id");
        var _href="/recipes/"+_cid+"/"+_c+"/"+_nid+"/"+_n+".html";
        //document.location.href = 'http://www.trevigourmet.com/#' + key + '_' + _n;
        if (document.location.href.indexOf('#') == -1) {
            document.location.href += '#';
        }
        if (document.location.href.indexOf('__') != -1) {
            var tmp = document.location.href.split('__');
            document.location.href = tmp[0] + ':' + _cid + '__' + _n;
        } else {
            document.location.href += ':' + _cid + '__' + _n;     
        }
        
        
        
        $('#b_button').unbind('click').bind('click', function () {
            window.open('/proj/trevireceipts/html__/send_recipe.php?id='+_nid, '', 'status=no, scrollbars=no, height=150, width=300');
        });

        if (!$('#i-data').length && !noTrack)
        {
            if((typeof(pageTracker) == "object") && typeof(pageTracker._trackPageview) == "function")
            {
                pageTracker._trackPageview(_href);
            }
        }

        var img = new Image();
        img.src=_img + "photos/"+id+".jpg"+"?"+Math.random();
        img.style.display="none";
        img.onload = function()
        {
            /*$("#image").createAppend(
                'img', {src:this.src,id:"img_new",width:"875",height:"446"}
                );
            */
            $('#image').append('<img id="img_new" src="'+this.src+'" width="875" height = "446" />');
            $("#img_new").animate({opacity:0.01}, 5, function()
                {
                    $("#img_new").css({display:"block"});
                    var html = "<p>{ingredients}</p><p>{timing}</p><p>{directions}</p><br /><p><a onclick='Main.print();return false;' href='' class='print'><img width='12' height='14' border='0' alt='print version' src='" + _img + "print.gif'/>&nbsp;print version</a></p>";

                    html += "";

                    html = ($("i[a='d']", Data.item).text() != '-') ? html.replace("{directions}", ('<b>Directions</b><br />' + $("i[a='d']", Data.item).text())) : html.replace("{directions}", '');
                    html = ($("i[a='t']", Data.item).text() != '-') ? html.replace("{timing}", ('<b>Timing</b><br />' + $("i[a='t']", Data.item).text())) : html.replace("{timing}", '');
                    html = ($("i[a='i']", Data.item).text() != '-') ? html.replace("{ingredients}", ('<b>Ingredients</b><br />' + $("i[a='i']", Data.item).text())) : html.replace("{ingredients}", '');
                    
                    html = html.replace(/\{id\}/gi, _nid);
                    html = html.replace(/\{url\}/gi, _href);
                    html = html.replace(/\{name\}/gi, _nm);
                    html = html.replace(/\{meta_title\}/gi, $("i[a='mt']", Data.item).text());
                    html = html.replace(/\{meta_keyword\}/gi, $("i[a='mk']", Data.item).text());
                    html = html.replace(/\{meta_description\}/gi, $("i[a='md']", Data.item).text());

                    $("#content").html(html.replace(/\n/g, "<br />"));
                    $("#h1").html($(Data.item).attr("name") + '<span style="display:none" id="prid">' + $(Data.item).attr("id") + '</span>'); //$(Data.item).attr("id")
                    document.title = 'TreviGourmet :: ' + $(Data.item).attr("name");
                    $("#content").jScrollPane({maintainPosition: false});
                    $("#img_new").animate({opacity:1}, 1200, function()
                        {
                            $("#img").remove();
                            $("#img_new").attr("id", "img");
                        }
                    );
                }
            );
        }
    },

    print : function()
    {
        myWindow = window.open("/proj/trevireceipts/html__/print.html", "tinyWindow", 'status=no, scrollbars=yes, height=500, width=550');
    },

    receiptShowForm : function()
    {
        
    },

    toggleBody : function(act)
    {
        var action = parseInt($("img", $("#btnhs")).css("top"))?"show":"hide";
        if(action == "hide")
        {
            $("#btnhs").animate({left:920}, 500, function()
                {
                    $("img", $("#btnhs")).css({top:"-36px"});
                }
            );
            $("#plaha").animate({left:921}, 500);
        }
        else
        {
            $("#btnhs").animate({left:862}, 500, function()
                {
                    $("img", $("#btnhs")).css({top:0});
                }
            );
            $("#plaha").animate({left:400}, 500);
        }
    }
};

var Interface = {
    playCookies : function()
    {
        jQuery.each($("#cookies .cookie"), function()
            {
                var id = parseInt($(this).attr("id").replace("cookie", ""));
                setTimeout("Interface._playCookie("+id+")", id*1000);
            }
        );
    },
    
    _playCookie : function(id)
    {
        var left = parseInt($("#cookies #cookie"+id).css("left").replace("px", ""))-1000;
        $("#cookie"+id+" .vilka").css({display:"block"});
        $("#cookie"+id).animate({left:left}, 800, function()
            {
                $("#cookie"+(id)+" .vilka").animate({top:-290}, 300, function()
                    {
                        
                    }
                );
            }
        );
    },

    highlightItems : function()
    {
        //alert('s');
        jQuery.each($(".item .img img"), function()
            {
                var id = $(this).parent().attr("id");
                $(this).bind("click", function()
                    {
//                    debugger;
                        
                        Main.loadReceipt(id, $(this).parent().attr("href"));
                        return false;
                    }
                );
                $(this).bind("mouseover", function()
                    {
                        $(this).parent().parent().css({backgroundColor:"white"});
                        $(this).animate({opacity:.4}, 100, function()
                            {
                                $(this).animate({opacity:1}, 50, function()
                                    {
                                        $(this).animate({opacity:.6}, 80, function()
                                            {
                                                $(this).animate({opacity:1}, 50, function()
                                                    {
                                                        $(this).parent().parent().css({backgroundColor:"transparent"});
                                                    }
                                                );
                                            }
                                        );
                                    }
                                );
                            }
                        );
                    }
                );
            }
        );
    }
};

var Data = {
    data : null,
    item : null,
    featured : null,

    load: function()
    {
        if ($('#i-data').length)
        {
            Data.data = $('#i-data');
            return true;
        }

        var href = document.location.href;
        var cid = 0;

        if (m = href.match(/recipes\/([^/]+)\//))
        {
            cid = m[1];
        } else if ( m = href.match(/recipe(\d{0,}):(\d{0,})/) ) {
            cid = m[2];
        } 
        
        if (cid == undefined) {
            cid = 0;
        }
        Main.loadData("/proj/trevireceipts/html__/data.php?" + (cid ? ('cid=' + cid) : 'top=1'), function () {
            //    debugger;
    //                $('#left').css({visibility: 'visible'});
    //                $('#right').css({visibility: 'visible'});
            var href = document.location.href;
            if ( m = href.match(/recipe(\d{0,}):(\d{0,})/) ) {
                //alert(m[1]);
                Main.loadReceipt(m[1], m[2]);
            } 
        });
        
    },
    
    loadItems : function(catId)
    {
        return $("i[a='r']", $("b", Data.data));
    },

    loadItem : function(id)
    {
        return Data.item = $("i[id='"+id+"']", Data.data);
    }
};

function loadSound()
{
    var sounds = [
        "/proj/trevireceipts/i/sound/rachmaninov-italian-polaka.mp3",
        "/proj/trevireceipts/i/sound/rimsky-korsakov-bumble-bee-flight.mp3",
        "/proj/trevireceipts/i/sound/tchaikovsky-napoletana.mp3"
    ];

    $('#snd').media({
        width:     115,
        height:    25,
        src:       "/proj/trevireceipts/i/sound/snd.swf?mp3String="+sounds.join(";"),
        attrs:     { wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"sameDomain"},  // object/embed attrs 
        params:    { wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"sameDomain"} // object params/embed attrs 
    });
};

rotateOpenX = function()
{
    return false;
    var ids = ["a66c390a", "aabb8501"];
    var d= null;
    for(i=0;i<ids.length && (d=document.getElementById(ids[i]));i++)
    {
        d.src=d.src.replace(/cb=[a-zA-Z0-9-_]+(&.*)?/, 'cb='+Math.floor(Math.random()*99999999999)+'$1');
    }
}
