var site = 'http://www.abworldfoods.com/';
var tempDivId = "";
var catClicked = "";
function loadForm(id) {
    $('#bottom-' + id).hide();
    $('#dform-' + id).show(1000, function() {
        $(this).slideDown();
        $("#container .item").css('height','auto');
        $("#container").masonry('reload');
    });
}

//filters
$(function() {

    $('.loginbutton').mouseover(function() {
        $(this).attr('src', './images/loginon.png');
    });
    $('.loginbutton').mouseout(function() {
        $(this).attr('src', './images/login.png');
    });

    $('.searchbutton').mouseover(function() {
        $(this).attr('src', './images/searchbtnon.png');
    });
    $('.searchbutton').mouseout(function() {
        $(this).attr('src', './images/searchbtn.png');
    });

    $('#searchF').submit(function(e) {
		
        $('#container').html("<div id='loader' align='center'><br/><br/><br/><img src='./images/ajax-loader-container.gif' /></div>");
        $("#clockContainer").remove();
        $('#filters li').each(function(index) {
            if ($(this).attr('id') != "deselect") {
                var $catFilter = $("input[type=submit]", this);
                //toggle images
                var $catTick = $("img", this);
                var $catFilterHidden = "#fcat-" + $(this).attr('id');
                $catTick.css('display', 'block');
                $($catFilterHidden).val(1);
            }
        });
        var kw = $('#keywords').val();
        if (kw.replace(/\s/g, "") != "") {
            History.pushState({
                state: 1,
                rand: Math.random()
            }, "Search - " + kw, site + '/search/' + kw + '/');

            abwModules(2, kw, null);
            $('html, body').animate({
                scrollTop: 0
            }, 'slow');
        }

        e.preventDefault();
    });

    $('#filters li').click(function(e) {
	
        if ($(this).attr('id') == "deselect") {
            $('html, body').animate({
                scrollTop: 0
            }, 'slow');
            var $catTick = $("img", this);
            if ($catTick.css('display') == "block") {
                $catTick.css('display', 'none');

                $('#filters li').each(function(index) {
                    if ($(this).attr('id') != "deselect") {
                        var cat = '.block-' + $(this).attr('id');
                        var $catTick = $("img", this);
                        var $catFilterHidden = "#fcat-" + $(this).attr('id');
                        if ($catTick.css('display') == "block") {
                            $($catFilterHidden).val(1);
                            $catTick.css('display', 'block');

                           
                        }
                    }
                });
				
				
            } else {
                $catTick.css('display', 'block');
                $('#filters li').each(function(index) {
                    if ($(this).attr('id') != "deselect") {
                        var cat = '.block-' + $(this).attr('id');
                        var $catTick = $("img", this);
                        var $catFilterHidden = "#fcat-" + $(this).attr('id');
                        if ($catTick.css('display') == "block") {
                            $($catFilterHidden).val(0);
                            $catTick.css('display', 'none');
                            $("#container").children().fadeOut("fast",function(){
                                //$("#container").remove();
                                $(this).remove();
								
                            });
							
                        }
                    }
                });
				
                return false;
            }

        } else {
			
			 
            var catClass = '.block-' + $(this).attr('id');

            var $catFilter = $("input[type=submit]", this);
            //toggle images
            var $catTick = $("img", this);
            var $catFilterHidden = "#fcat-" + $(this).attr('id');

            if ($catTick.css('display') == "block") {
                $($catFilterHidden).val(0);
                $catTick.css('display', 'none');
                $("#container").children(catClass).fadeOut("fast",function(){
                    //$("#container").remove();
                    $(this).remove();
					
                });
                $("#container").masonry("reload");
            } else {
                // DESELECT ALL
                $('#filters li').each(function(index) {
                    if ($(this).attr('id') != "deselect") {
                        var cat = '.block-' + $(this).attr('id');
                        var $catTick2 = $("img", this);
                        var $catFilterHidden2 = "#fcat-" + $(this).attr('id');
                        if ($catTick2.css('display') == "block") {
                            $($catFilterHidden2).val(0);
                            $catTick2.css('display', 'none');
                            $("#container").children().fadeOut("fast",function(){
                                //$("#container").remove();
                                $(this).remove();
								
                            });
							
                        }
                    }
                });
                $("#container").masonry("reload");
                // SELECT ONE
                var $DETick = $("#deselect img");
                $DETick.css('display', 'none');
				 
                $($catFilterHidden).val(1);
                $catTick.css('display', 'block');

            }
            abwModules(4, null, null);

			

        }
        return false;
        e.preventDefault();
    });
});

function abwModules(init, $keywords, id) {
    var aCats = $('#filters form').serialize();
    var datas = "";
    //	alert(id + " " + init);

    if (($keywords != null) && (init == 2)) {
        datas = '&action=search&keywords=' + $keywords + '&page=1';
    } else if ((id != "") && (init == 3)) {
        datas = '&action=related&cid=' + id + '&page=1';
    } else if (init == 4){
        datas = aCats + '&action=filter' + '&page=1';
    }else {
        datas = aCats + '&page=1';
    }
	
    $.ajax({
        url: 'ajax/',
        data: datas,
        dataType: 'json',
        success: function(data) {
			
            if (init == 1) {
                var clockVar = loadClocks();
                $("#container").prepend("<div id='clockContainer' class='item'></div>");
				 
                $("#clockContainer").append(clockVar).fadeIn();
                //$(clockVar).appendTo("#clockContainer");
  				
                setCanada();
                setPoland();
                setUK();
                setAus();
                setThai();
				
            }
			
			
            
            if (init == 1) {
                loadModules(data);
                initMans($keywords,init);
			
				
            }else if (init == 4){
				
                $("#clockContainer").remove();
                filterModules(data);
                initMans($keywords,init);
                var $container = $('#container');
                //$container.imagesLoaded(function() {$container.masonry("reload");});
                $container.masonry("reload");
				
            }else if ((init == 2) || (init == 3)) {
                loadModules(data);
                if(init == 3){
                    $("#clockContainer").remove();
                }
                var $container = $('#container');
                //$container.imagesLoaded(function() {$container.masonry("reload");});
                $container.masonry("reload");
            }
            
        }
    });
}

function filterModules($content){
    if($content != null){
        //alert(catClicked);
        var $data = $content.html;
        var catfound = $content.catfound;
        var nextpage = $content.nextpage;
        if ($data.length > 0) {
            $("#loader").remove();
            $("#page-nav").remove();
            var arrayElements = new Array();
            $("div[id^='data-']").each(function(index) {
				
                arrayElements[index] = $(this).attr("id");
				
            });
			
            var append = "";
            var delayCounter = 0;
            for (x in $data) {
				
                var objCont = $data[x].object;
                var objId = $data[x].id;
                //alert(arrayElements.length + " - " + $data.length);
                if(arrayElements.length > 0 ){
					
					
                    if ($('#container').compareElements("div#" + objId) == false) {
                        if($data[x].id != arrayElements[x]){
                            delayCounter ++;
                            $($data[x].object).insertAfter('#' + arrayElements[x]).delay(800 + 700 * delayCounter).fadeIn();
                            //$("#" + objId + " .img-main").preloadImage("#" + objId);
                            $("#" + objId + " .img-main").onImagesLoaded(function(_this){
                                $(_this).fadeIn(3000);
								
                            })
							
							
                        }
						
                    }
                }else{
                    $(objCont).hide().appendTo('#container').delay(800 + 700 * x).fadeIn();
                    $("#" + objId + " .img-main").onImagesLoaded(function(_this){
                        $(_this).fadeIn(3000);
						
                    })
					
                }
	
            }
			
            $('.ajax').unbind('click');
            $('.ajax').bind('click', function(e) {
                loadPage(($(this).attr('href')), $(this));
                e.preventDefault();
            });	
			
	
        }
		
        if(nextpage != null){
            $("#container").append(nextpage);
        }
		
        if (catfound != null) {
            var $catfoundarray = catfound.split(",");
	
            if ($catfoundarray.length > 0) {
                $('#filters li').each(function(index) {
                    if ($(this).attr('id') != "deselect") {
	
                        //toggle images
                        var $catTick = $("img", this);
                        var $catFilterHidden = "#fcat-" + $(this).attr('id');
                        $catTick.css('display', 'none');
                        $($catFilterHidden).val(0);
                        for (x in $catfoundarray) {
                            if ($catfoundarray[x] == $(this).attr('id')) {
                                $catTick.css('display', 'block');
                                $($catFilterHidden).val(1);
                            }
                        }
	
                    }
                });
            }
        }
    }else{
        //content null
		
        $("#container").children().fadeOut("fast",function(){
            $(this).remove();
			
        });
		
    }
}

function loadModules($content) {
    if($content != null){
        var $data = $content.html;
        var catfound = $content.catfound;
        var nextpage = $content.nextpage;
        var kw = "";
        if ($data.length > 0) {
            $("#loader").remove();
            var items = '';
            for (x in $data) {
	
                var objCont = $data[x].object;
                var objId = $data[x].id;
	
                if ($('#container').compareElements("div#" + objId) == false) {
                    //alert("appending");
					
                    $(objCont).hide().appendTo('#container').delay(800 + 700 * x).fadeIn("slow");
                    $("#" + objId + " .img-main").onImagesLoaded(function(_this){
                        $(_this).fadeIn(3000);
						
                    })
						
                }
		
            }
	
        }
		
	
		
		
		
		
        $('.ajax').unbind('click');
        $('.ajax').bind('click', function(e) {
            loadPage(($(this).attr('href')), $(this));
            e.preventDefault();
        });
        if(nextpage != null){
            $("#container").append(nextpage);
        }
        if (catfound != null) {
            var $catfoundarray = catfound.split(",");
	
            if ($catfoundarray.length > 0) {
                $('#filters li').each(function(index) {
                    if ($(this).attr('id') != "deselect") {
	
                        //toggle images
                        var $catTick = $("img", this);
                        var $catFilterHidden = "#fcat-" + $(this).attr('id');
                        $catTick.css('display', 'none');
                        $($catFilterHidden).val(0);
                        for (x in $catfoundarray) {
                            if ($catfoundarray[x] == $(this).attr('id')) {
                                $catTick.css('display', 'block');
                                $($catFilterHidden).val(1);
                            }
                        }
	
                    }
                });
            }
        }
    }
};

//function to check element exists
(function($) {
    $.fn.compareElements = function($search) {
        if ($(this).find($search).length) {
            return true;
        } else {
            return false;
        }
    }
})(jQuery);

(function($){
    $.fn.preloadImage = function(objId){
        // wrap our new image in jQuery, then:
        $(this)
		  	
        // once the image has loaded, execute this code
        .load(function () {
			
            // fade our image in to create a nice effect
            $(this).fadeIn(3000);
        })			
        // if there was an error loading the image, react accordingly
        .error(function () {
            // notify the user that the image could not be loaded
            });
			
			
    }
})(jQuery);

//function to fade in and show modules
(function($) {
    $.fn.showdelay = function($time) {
        if ($time == "") {
            $time = 250;
        }
        var delay = 250;
        return this.each(function() {
            if ($(this).is(":hidden")) {
                $(this).delay(delay).fadeIn(delay);
            }

            delay += delay;
        });
    };
})(jQuery);

function initMans($keywords,init) {
	
    $(function() {
        var aCats = $('#filters form').serialize();
        var datas = "";
        if ($keywords != "") {
            datas = 'keywords=' + $keywords + '&page=1';
        } else {
            datas = aCats + '&page=1';
        }
        var $container = $('#container');
        // $container.imagesLoaded(function() {
        if(init == 4){
        }else{
            $container.masonry({
                itemSelector: '.item',
                columnWidth: 1,
                isAnimated: true,
                isFitWidth: true
            });
			
        }
            
    // });
	
    /* $container.infinitescroll(
			{
				navSelector: '#page-nav',
				nextSelector: '#page-nav a',
				itemSelector: '.item',
				ajaxData: datas,
				extraScrollPx: 0,
				animate: true,
				errorCallback: function(){
					alert("error");
				}
			}, 
		
			// call Masonry as a callback
			function(newElements) {
				
				var $data = (newElements.html);
				var nextpage = newElements.nextpage;
				// ensure that images load before adding to masonry layout
				//$newElems.imagesLoaded(function(){
				$("#loader").remove();
				$("#page-nav").remove();
				for (x in $data) {
					
					var objCont = $data[x].object;
					var objId = $data[x].id;
					//alert(arrayElements.length + " - " + $data.length);
						
					if ($('#container').compareElements("div#" + objId) == false) {
						$(objCont).hide().appendTo('#container').delay(800 + 700 * x).fadeIn();
						$("#" + objId + " .img-main").onImagesLoaded(function(_this){
							$(_this).fadeIn(3000);
							
						});
						
					}
					
		
				}
				
				$container.masonry('reload');
				if(nextpage != null){
					$("#container").append(nextpage);
				}
				$('.ajax').unbind('click');
				$('.ajax').bind('click', function(e) {
					loadPage(($(this).attr('href')), $(this));
					e.preventDefault();
				});
				//});
			}
		);*/

    });

}
function initPage() {

    var winLoc = (window.location).toString();
    //ajax bit
    //var winLoc = window.location.toString();
    var findS = winLoc.toLowerCase().indexOf("content/");
    if (findS >= 0) {
        var subUrl = winLoc.substr(findS, winLoc.length);
        locArray = subUrl.split("/");
        var cid = locArray[1];
        modContent(cid, "", winLoc);
    }else{
        abwModules(1); //init
    }
}
function loadPage($href, $divObject) {
    var winLoc = ($divObject.attr("href")).toString();
    //ajax bit
    //var winLoc = window.location.toString();
    var findS = winLoc.toLowerCase().indexOf("content/");
    if (findS >= 0) {
        var subUrl = winLoc.substr(findS, winLoc.length);
        locArray = subUrl.split("/");
        var cid = locArray[1];
        modContent(cid, $divObject, $href);
    }
}

function modContent(id, $divObject, $href) {
    //alert(id);
    $.ajax({
        url: site + '/ajax/',
        dataType: 'json',
        data: 'action=full' + '&cid=' + id,
        //onLoading: showLoadLarge,
        success: function(data) {
            if ($href) {
                var State = History.getState();
                var findCid = State.url.toLowerCase().indexOf(id);
                if (findCid < 0) {

                    History.pushState({
                        state: 1,
                        rand: Math.random()
                    }, data.title, $href);
                }

            }
			
            if($('#data-' + id).length == 0){
                $("#container").prepend('<div id="data-' + id + '" class="item"></div>');
				
            }
			
            var clickedDiv = $('#data-' + id);
            //remove 
            $("div[id^='data-']").each(function(index) {
				
                if($(this).attr("id") != 'data-' + id){
                    $(this).delay(150 ).fadeOut().remove();
                }
            });
            
            $("#img-" + id).removeClass("img-load");
            $("#img-" + id + " img").attr("src", "./images/loader.gif");
            //animate small to large
            clickedDiv.css("z-index", 10);
            clickedDiv.delay(1000).animate({
                top:'0px', 
                left:'0px'
            },500,"linear",function(){ 
                $('html, body').animate({
                    scrollTop: 0
                }, 'slow');
                $('#data-' + id + " .content").animate({
                    width: '564px'
                },300,"linear");
                $('#img-' + id + "").animate({
                    width: '564px'
                },300,"linear");
                $('#data-' + id + " .bottom").animate({
                    width: '564px'
                },300,"linear");
                $('#data-' + id + " .title").animate({
                    width: '564px'
                },300,"linear");
                $('#data-' + id + " .subtitle").animate({
                    width: '564px'
                },300,"linear");
                $(clickedDiv).animate({
                    width: '574px'
                },500,"linear",function(){ 
				
                    $(this).html(data.html[0].object).animate({
                        height: $(this).outerHeight() + 'px'
                        }, 'fast' );
                    $image = $("#img-" + id + " img");
					
					
                    $image.onImagesLoaded(function(_this){
                        $(_this).fadeIn(1500);
                        abwModules(3,null,id);
                    })
					
                    $("#container").masonry('reload');
                });
				 
            });
			
			
			
        }
    });

}
$.fn.onImagesLoaded = function(_cb) { 

    return this.each(function() {
 
        var $imgs = (this.tagName.toLowerCase()==='img')?$(this):$('img',this),
        _cont = this,
        i = 0,
        _done=function() {
		
            if( typeof _cb === 'function' ) _cb(_cont);
	  
        };
 	
        if( $imgs.length ) {
            $imgs.hide();
            $imgs.each(function() {
		  
                // var $imgC = $(this);
                // $imgC.parent().addClass("img-load");
		 
                var _img = this,
                _checki=function(e) {
			
                    if((_img.complete) || (_img.readyState=='complete'&&e.type=='readystatechange') )
                    {
                        if( ++i===$imgs.length ){
				
                            _done();
				
				 
					
				
				
                        }else{
                    //alert("loading");
                    }
                    }
                    else if( _img.readyState === undefined ) // dont for IE
                    {
                        $(_img).attr('src',$(_img).attr('src')); // re-fire load event
                    }
                }; // _checki \\
 
                $(_img).bind('load readystatechange', function(e){
                    _checki(e);
                });
                _checki({
                    type:'readystatechange'
                }); // bind to 'load' event...
            });
        } else _done();
    });
};


function loadClocks(){
	
		 
    var clock = "";

    clock += '<div id="data-clock1"> <div class="tl"><div class="tr"></div></div> <div class="bl"> <div class="br"><div class="content box2" id="c-holder"> <div class="mask-tl"></div> <div class="mask-tr"></div> <div class="mask-bl"></div> <div class="mask-br"></div> <div class="content-inner"> <div class="content-top"> <div  style="width:182px; height:165px;" class="img-clock-aus"><div id="clock"><div id="hour"><img src="./images/hourHand.png" /></div><div id="minute"><img src="./images/minuteHand.png" /></div> </div></div> </a> </div> </div> </div> </div> </div> </div>';
	
	
    clock += '<div id="data-clock2"> <div class="tl"><div class="tr"></div></div> <div class="bl"> <div class="br"><div class="content box2" id="c-holder"> <div class="mask-tl"></div> <div class="mask-tr"></div> <div class="mask-bl"></div> <div class="mask-br"></div> <div class="content-inner"> <div class="content-top"> <div  style="width:182px; height:165px;" class="img-clock-thai"><div id="clock"><div id="hour"><img src="./images/hourHand.png" /></div><div id="minute"><img src="./images/minuteHand.png" /></div> </div></div> </a> </div> </div> </div> </div> </div> </div>';
	

    clock += '<div id="data-clock3" > <div class="tl"><div class="tr"></div></div> <div class="bl"> <div class="br"><div class="content box2" id="c-holder"> <div class="mask-tl"></div> <div class="mask-tr"></div> <div class="mask-bl"></div> <div class="mask-br"></div> <div class="content-inner"> <div class="content-top"> <div  style="width:182px; height:165px;" class="img-clock-uk"><div id="clock"><div id="hour"><img src="./images/hourHand.png" /></div><div id="minute"><img src="./images/minuteHand.png" /></div> </div></div> </a> </div> </div> </div> </div> </div> </div>';
	

    clock+= '<div id="data-clock4" > <div class="tl"><div class="tr"></div></div> <div class="bl"> <div class="br"><div class="content box2" id="c-holder"> <div class="mask-tl"></div> <div class="mask-tr"></div> <div class="mask-bl"></div> <div class="mask-br"></div> <div class="content-inner"> <div class="content-top"> <div  style="width:182px; height:165px;" class="img-clock-poland"><div id="clock"><div id="hour"><img src="./images/hourHand.png" /></div><div id="minute"><img src="./images/minuteHand.png" /></div> </div></div> </a> </div> </div> </div> </div> </div> </div>';
	
    clock+= '<div id="data-clock5" > <div class="tl"><div class="tr"></div></div> <div class="bl"> <div class="br"><div class="content box2" id="c-holder"> <div class="mask-tl"></div> <div class="mask-tr"></div> <div class="mask-bl"></div> <div class="mask-br"></div> <div class="content-inner"> <div class="content-top"> <div  style="width:182px; height:165px;" class="img-clock-canada"><div id="clock"><div id="hour"><img src="./images/hourHand.png" /></div><div id="minute"><img src="./images/minuteHand.png" /></div> </div></div> </a> </div> </div> </div> </div> </div> </div>';
	
	
	
    return clock;
}
