/*
 * @author Sadique Mohammed
 * @email  sadiqmd@hotmail.com
 * @date  Jan 4, 2011
 * @file  lk
 */

(function($){
    var methods = {
        init: function(options){
            return $(this).each(function(i,el){
                var $el = $(el);
                var class_name   = $el.attr('class');
                var method_name;
                if(class_name){
                    method_name = 'sm_'+class_name;
                }

                if($el.is('form')){
                    try{
                        $(el).bind('submit',methods.process);
                    }catch(e){
                        writetoConsole(e);
                    }
                }
                if($el.is('input')){
                    try{
                        if($el.attr('type') == 'checkbox'){
                            $el.bind('change',{
                                element:$el
                            },methods[method_name]);
                        }

                        if($el.attr('checked')){
                            $el.trigger('change');
                        }
                    }catch(e){
                        writetoConsole(e);
                    }
                }
                if($el.attr('class') == 'upload'){
                    $el.smUpload(method_name);
                }
            });
        },
        process: function(e){
            e.preventDefault();
            $this   = $(this);
            $("#sm-overlay").show();
            $this.ajaxSubmit({
                dataType: 'json',
                success: methods.parse
            });
        },
        parse: function (response) {
            $("#sm-overlay").hide();
            if(response.success){
                try{
                    if(response.redirect_url){
                        window.location = response.redirect_url;
                    }
                }catch(e){
                    writetoConsole(e);
                }
            }
            for(k in response.result){
                if(response.result[k].error){
                    methods.render_error(response.result[k]);
                }else{
                    methods.remove_error(response.result[k]);
                }
            }
            try{
                for(k in response.jsCallback){
                    eval(response.jsCallback[k]);
                }
            }
            catch(e){
                writetoConsole(e);
            }
        },
        render_error: function (el) {
            var err_el  = el.id + '_error';
            if(!$('#'+err_el).is('span')){
                var span = document.createElement('span');
                span.id  = err_el;
                span.className = 'error';
                span.textContent    = el.error;
                $('#'+el.id).parent().append(span);
                $(span).fadeIn();
            }
            else{
                $('#'+err_el).text(el.error);
            }
        },
        remove_error: function(el) {
            var err_el  = el.id + '_error';
            if($('#'+err_el).is('span')){
                $('#'+err_el).fadeOut(2500, function(){
                    $('#'+err_el).remove();
                })

            }
        },
        sm_toggle: function(el){
            var el_id   = el.data.element.attr('id');
            var content_id = el_id+'_container';
            try{
                $('#'+content_id).slideToggle(1000);
            }catch(e){
                writetoConsole(e);
            }
        },
        smUploadSuccess: function (file,data) {
            var object = jQuery.parseJSON(data);
            methods.parse(object);
            var progress = new FileProgress(file,  this.customSettings.upload_target);
            progress.setStatus("");
            progress.setProgressNameNull();
            progress.toggleCancel(false);

        },
        sm_upload: function(){
            if(!$(this).attr('id')){
                return false;
            }
            var _progress_container = $(this).attr('id') + '_progress_container';
            var upload_path = $(this).attr('alt');
            $('#'+_progress_container).css('height','auto');
            var _csrf_token = $('#file__csrf_token').val();
            var _file_name   = $('#file_name').val();

            $('#file_name').bind('change', function(){
                swfu.addPostParam('file[name]',this.value);
            })
            $('#file__csrf_token').bind('change', function(){
                swfu.addPostParam('file[_csrf_token]',this.value);
            })


            var swfu    = new SWFUpload({
                // Backend Settings
                upload_url: upload_path,
                // File Upload Settings
                file_size_limit : "10 MB",
                file_types : "*.jpg;*.png",
                file_types_description : "Web Images",
                file_upload_limit : 0,
                file_post_name: 'file[file_path]',
                post_params: {
                    'file[_csrf_token]': _csrf_token,
                    'file[name]': _file_name,
                    'file[mime_type]':'image'
                },
                //
                // Event Handler Settings - these functions as defined in Handlers.js
                //  The handlers are not part of SWFUpload but are part of my website and control how
                //  my website reacts to the SWFUpload events.
                swfupload_preload_handler : preLoad,
                swfupload_load_failed_handler : loadFailed,
                file_queue_error_handler : fileQueueError,
                file_dialog_complete_handler : fileDialogComplete,
                upload_progress_handler : uploadProgress,
                upload_error_handler : uploadError,
                upload_success_handler : methods.smUploadSuccess,
                //upload_complete_handler : uploadComplete,

                // Button Settings
                button_image_url : SITEURL+ "/images/SmallSpyGlassWithTransperancy_17x18.png",
                button_placeholder_id : $(this).attr('id'),
                button_width: 180,
                button_height: 18,
                button_text : '<span class="button">Select File</span>',
                button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 12pt; } .buttonSmall { font-size: 10pt; }',
                button_text_top_padding: 0,
                button_text_left_padding: 18,
                button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
                button_cursor: SWFUpload.CURSOR.HAND,

                // Flash Settings
                flash_url : SITEURL+"/js/swfupload/swfupload.swf",
                flash9_url : SITEURL+"/js/swfupload/swfupload_fp9.swf",

                custom_settings : {
                    upload_target : _progress_container,
                    /*thumbnail_height: 400,
                    thumbnail_width: 400,*/
                    thumbnail_quality: 100
                },

                // Debug Settings
                debug: false
            })

        }

    };


    $.fn.smForm = function (method) {
        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        }else if(typeof method === 'object' || ! method){
            return methods.init.apply(this,arguments)
        }else{
            return $.error('Method '+method + ' does not exist!' );
        }
    };
    $.fn.smToggle = function (method) {
        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        }else if(typeof method === 'object' || ! method){
            return methods.init.apply(this,arguments)
        }else{
            return $.error('Method '+method + ' does not exist!' );
        }
    }
    $.fn.smUpload = function (method) {
        if ( methods[method] ) {
            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
        }else if(typeof method === 'object' || ! method){
            return methods.init.apply(this,arguments)
        }
        else{
            return $.error('Method '+method + ' does not exist!' );
        }
    }

})(jQuery)

var smfh;
$(document).ready(function() {
    $('body').append('<div id="sm-overlay"> </div>');
    $("#sm-overlay").css('opacity','0.5')
        .css('z-index','10000')
        .css('width','100%')
        .css('position','absolute')
        .css('top','0')
        .css('height',$(window).height());
    $('form.sm_ajax_form').smForm();
    $('input.toggle').smToggle();
    $('input.upload').smUpload();
    $('a.empty').live('click',function(){
        var id  = $(this).attr('atitle');
        $('#'+id).val('');
        return false;
    });
    try{
        $('div.message').show().fadeOut(300);
    }catch(e){
        writetoConsole(e);
    }

    smfh    = new smFileHandler();
    $('.activeimage').live('click',function(){
        alert(this.id)
    });

    $('#slides').slides({
        preload: true,
        preloadImage: SITEURL+'images/loading.gif',
        play: 5000,
        pause: 36000,
        hoverPause: true,
        effect: 'fade'
    });
   
    try{
        $("#accordion h2").each(function(i,el){
            if(el.id){
                var c_id    = el.id.replace('h','c');
                $('#'+c_id).addClass('accordion_container').hide();
                
                $(el).bind('click',function(e){
                    $('#accordion h2').removeClass('active').find('span').text('+');
                    var remove_sign = true;
                    $('.accordion_container').each(function(j,jel){
                        if(c_id != jel.id){
                            $(jel).slideUp();
                            $(el).find('span');
                            if(remove_sign){
                                $(el).find('span').text('-');
                            }
                        }
                        if(c_id == jel.id){
                            if($(jel).css('display')=='none'){
                                $(jel).slideDown('slow');
                                $(el).addClass('active');
                            }else{
                                $(jel).slideUp('slow');
                                $(el).removeClass('active').find('span').text('+');
                                remove_sign = false;
                            }
                            
                        }
                    });
                })
            }
        });
    }catch(e){
        writetoConsole(e);
    }

    try{
    var old_value = 0;
        $('div.lkslides_container img,div.lkslides_container div').each(function(i,el){
            var value1  = $(el).height();
            max_value = Math.max(old_value, value1);
            old_value   = max_value;
            $(this).parent().css({
                'height' : max_value,
                'overflow' : 'hidden'
            });
        });
    }catch(e){
        writetoConsole(e);
    }

    try{
        $('div.loadmap').each(function(i,el){
            var lat_long    = $(el).attr('title').split('|');
            var myLatlng = new google.maps.LatLng(lat_long[0], lat_long[1]);
            var address = $('#'+lat_long[2]).html();
            var myOptions = {
                zoom: 10,
                center: myLatlng,
                mapTypeControlOptions: {
                    mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID]
                },
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            var mymap = new google.maps.Map(document.getElementById(el.id), myOptions);

            var marker = new google.maps.Marker({
                position: myLatlng,
                map: mymap,
                title:"Lakshya Digital Private Ltd",
                infoWindow: new google.maps.InfoWindow({
                      content: address
                 })
            });
            google.maps.event.addListener(marker, 'click', function() {
                  this.infoWindow.open(mymap, this);
            });
        });
    }catch(e){
        writetoConsole(e);
    }

    if(!$('#container').hasClass('main')){
        $('#container').css('min-height', '420px');
    }

    try{
         $('#image_showcase').slides({
            preload: true,
            preloadImage: SITEURL + '/images/loading.gif',
            play: 5000,
            pause: 2500,
            effect: 'fade',
            hoverPause: true
        });
    }catch(e){
        writetoConsole(e);
    }
    try{
        $('ul.portfolio li a img').each(function(i,el){
            var image   = el.src;
            el.src  = SITEURL+ '/images/loading.gif';
            $.ajax({
                url: image,
                success:function(d){
                    el.src  = image;
                }
            });
        });

        $("a[rel*=facebox]").fancybox({
            'titleShow'     : true,
            'transitionIn' : 'elastic',
            'transitionOut': 'elastic',
            'easingIn'     : 'easeOutBack',
            'easingOut'    : 'swing',
            'overlayColor' : '#010606',
            'overlayOpacity' : 0.8,
            'titlePosition' : 'over', // 'float', 'outside', 'inside' or 'over'
            'titleFormat' : null,
            'titleFromAlt' : false,

            speedIn : 800,
            speedOut : 500,

            changeSpeed : 300,
            changeFade : 'fast',
            padding: 0
        });

    }catch(e){
        writetoConsole(e);
    }
    $('#navigation li.on').find("ul.subnav").slideDown('fast').show();
    $('#navigation li a').hover(function(e){
        $(this).parent().find("ul.subnav").slideDown('fast').show();
        $(this).parent().hover(function() {
            }, function(){
                $(this).parent().find("ul.subnav").each(function(i,el){
                    if(!$(el).parent().hasClass('on')){
                        $(el).slideUp('slow');
                    }
                })
                    
                
            });

    //Following events are applied to the trigger (Hover events for the trigger)
    }).hover(function() {
        $(this).addClass("subhover"); //On hover over, add class "subhover"
    }, function(){	//On Hover Out
        $(this).removeClass("subhover"); //On hover out, remove class "subhover"

    });
  
    
    try{
        $('div#accordion h2').append('<span>+</span>');
    }catch(e){
        writetoConsole(e);
    }
    try{
        $('a.showbig').live('click',function(e){
            e.preventDefault();
            var img    = new Image();
            img.src = this.href;
            $('.main-image').html(img);
            $(img).css({
                    opacity: 0
                        }).animate({
                               opacity: 1
                                });
            
            $('a.showbig').removeClass('current');
            $(this).addClass('current');
        });
    }catch(e){
        writetoConsole(e);
    }

    try{
        $('.portfolio_category .box33 li h2').css('cursor','pointer').click(function(e){
            window.location = $(this).find('a').attr('href');
        });

       
    }catch(e){
        writetoConsole(e);
    }

    try{
        function sm_accordion(){
            $this   = this;
            $('div#form_accordion h2').append('<span>+</span>');

            $("#form_accordion h2").each(function(i,el){
                if(el.id){
                    var c_id    = el.id.replace('h','c');
                    $('#'+c_id).addClass('accordion_container');
                    $this.hide(c_id);
                    if(i==0){
                         $this.slideDown(c_id);
                    }
                }
            });
        }

        sm_accordion.prototype.slideUp  = function(id) {
            var h_id    = id.replace('c','h');
            $('#'+id).slideUp();
            $('#'+h_id).removeClass('active').find('span').text("+");
        }

        sm_accordion.prototype.slideDown  = function(id) {
            var h_id    = id.replace('c','h');
            $('#'+id).slideDown();
            $('#'+h_id).addClass('active').find('span').text("-");
        }

        sm_accordion.prototype.hide  = function(id) {
            var h_id    = id.replace('c','h');
            $('#'+h_id).find('span').text("+");
            $('#'+id).hide();
        }

        sm_accordion.prototype.open  = function(id) {
            
        }
        sm_accordion.prototype.slideToggle  = function(id) {
            $this   = this;
            $('.accordion_container').each(function(i,el){
                $this.slideUp(el.id);
            });
            $this.slideDown(id);
        }

        sma = new sm_accordion();
        
        $('#copy_ltr').live('click',function(){
            var selected_objects = $('#skills_required').val();
            var selected_object = selected_objects.toString().split(',');

            var select = document.getElementById('applied_job_professional_skills');
            


            $(selected_object).each(function(i,el){
                var exist   = false;
                $('#applied_job_professional_skills option').each(function(j,op){
                    if(op.value==el){
                        exist = true;
                    }
                });
                if(!exist){
                    var opt = document.createElement('option');
                    opt.text = el;
                    opt.value = el;
                    try {
                        select.add( opt, null );
                    }catch(ex) {
                        select.add( opt );
                    }
                }
            });
            for(i=0;i<select.options.length;i++){
                select.options[i].selected = true;
            }
        });
        $('#copy_rtl').live('click',function(){
            var selected_objects = $('#applied_job_professional_skills').val();
            var selected_object = selected_objects.toString().split(',');
            $(selected_object).each(function(i,el){
                var exist   = false;
                $('#applied_job_professional_skills option').each(function(j,op){
                    if(op.value==el){
                       $(op).remove()
                    }
                });
            })
        })
    }catch(e){
        writetoConsole(e);
    }
    try{
        $('h2.tab a img').each(function(i,el){
            $(el).attr('ptitle', $(el).attr('title')).removeAttr('title');

        });
        $('h2.tab a').each(function(i, el){
            $(el).bind('click',function(e){
                e.preventDefault();
                $(this).parent().find('a').removeClass('active');
                $(this).addClass('active');

                var clicked = $(this).find('img').attr('ptitle');
                $(this).parent().find('img').each(function(j,jel){
                    var c_id    = $(jel).attr('ptitle');
                    if(c_id==clicked){
                        $('#'+c_id).slideDown('slow');
                    }else{
                        $('#'+c_id).slideUp('slow');
                    }
                })
            });

            if(i==0){
                $(el).trigger('click');
            }
        });
    }catch(e){
        writetoConsole(e);
    }
});


function writetoConsole(message) {
    try{
        console.log(message);
    }catch(e){}
}

smFileHandler   = function () {
    }
smFileHandler.prototype.init = function (params) {
    try{
        this.id  = params.file_id;
        this.name  = params.file_name;
        this.status  = params.file_status;
        this.thumb_url  = params.thumb_url;
    }catch(e){
        writetoConsole(e);
    }
}
smFileHandler.prototype.setParam    = function (params) {
    this.init(params);
}
smFileHandler.prototype.populateImage = function(elid){
    var div = document.createElement('div');
    div.setAttribute('class', 'image_block');
    $("#"+elid).append(div);
    var input = document.createElement('input');
    input.value = "Remove";
    input.setAttribute('class', 'activeimage');
    input.setAttribute('id', this.id);


    input2 = document.createElement('input');
    input2.value = this.id;
    input2.setAttribute('type', 'hidden');
    input2.setAttribute('name', 'portfolio[files_list][]');

    var img =  new Image();
    img.src = this.thumb_url;
    div.appendChild(img);
    div.appendChild(input);
    div.appendChild(input2);




}
smFileHandler.prototype.populateList = function(elid){
    var select = document.getElementById(elid);
    var opt = document.createElement('option');
    opt.text = this.name;
    opt.value = this.id;
    try {
        select.add( opt, null );
    }catch(ex) {
        select.add( opt );
    }
    for(i=0;i<select.options.length;i++){
        select.options[i].selected = true;
    }
}


function preload(images) {
    if (images) {
        var i = 0;
        var imageArray = new Array();
        imageArray = images.split(',');
        var imageObj = new Image();
        for(i=0; i<=imageArray.length-1; i++) {
            //document.write('<img src="' + imageArray[i] + '" />');// Write to page (uncomment to check images)
            imageObj.src= SITEURL+'/images/'+imageArray[i];
        }
    }
}

function synchForm(form_id) {
    //final_form
    $('#'+form_id+' input, select').each(function(i,el){
        var id  = el.id;
        if(el.type=='text'){
            $('#final_form input#'+id).val($(el).val());
        }
        if(el.type=='select-multiple'){
            try{
                $('#final_form input#'+id).val('');
            }catch(e){
                alert(e)
            }
            $('#final_form input#'+id).val($(el).val());
            
        }
    });

}
